0

私は以下のようなコードを持っています。

  class Student : IPeople
{
    private string name;
    public string Name
    {
        get { return name;}
        set { name = value;}
    }

    private bool sex;
    public bool Sex
    {
        get{ return sex; }
        set{ sex = value;}
    }

    private int age;
    public int Age
    {
        get{return age;}
        set{age = value;}
    }

    public virtual ICollection<Dog> dogs { get;set; }

    public Student()
    {
        dogs = new List<Dog>();
    }
}

class Pet
{
    string Name { get; set; }
    bool Sex { get; set; }
    int Age{get;set;}
}

class Dog : Pet
{
    public string Type { get; set; }
    public virtual ICollection<IPeople> persons { get; set; }

    public Dog()
    {
        persons = new List<IPeople>();
    }
}

コンテキストは

class TestContext : DbContext
{
    public DbSet<Student> studentSet { get; set; }
    public DbSet<Dog> dogSet { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().HasMany(x => x.dogs).WithMany(y => (ICollection<Student>)y.persons);
    }
}

以下のようなレコードを挿入すると、

using (TestContext context = new TestContext())
        {
            Student s = new Student();
            s.Age = 18;
            s.Sex = true;
            s.Name = "ts";
            Dog d = new Dog();
            d.Type = "abc";
            d.Sex = false;
            d.Name = "dog";
            d.Age = 3;
            s.dogs.Add(d);
            context.studentSet.Add(s);
            context.SaveChanges();
        }

すべてがうまく機能しますが、以下のようなレコードを挿入すると、Studentレコードはデータベースに挿入されません。

using (TestContext context = new TestContext())
        {
            Student s = new Student();
            s.Age = 18;
            s.Sex = true;
            s.Name = "ts";
            Dog d = new Dog();
            d.Type = "abc";
            d.Sex = false;
            d.Name = "dog";
            d.Age = 3;
            d.persons.Add(s);
            context.dogSet.Add(d);
            context.SaveChanges();
        }

誰でも助けることができますか?

4

1 に答える 1

3

ここではインターフェースを使用できませんIPeople

public virtual ICollection<IPeople> persons { get; set; }

ナビゲーションプロパティは、モデルのエンティティクラス(抽象または具象)を参照する必要があります。

People考えられる代替案は、インターフェースの代わりに抽象クラスを使用することかもしれません。ただし、ナビゲーションプロパティを配置する必要があります...

public virtual ICollection<Dog> dogs { get;set; }

...抽象クラスを参照しているStudentため、派生クラスではなく、その抽象クラスに次のようになります。Dog.personsPeople

abstract class People
{
    // ...
    public virtual ICollection<Dog> dogs { get;set; }
}

class Student : People
{
    // ...
}

class Pet
{
    // ...
}

class Dog : Pet
{
    // ...
    public virtual ICollection<People> persons { get; set; }
}

そして、マッピングは次のようになります。

modelBuilder.Entity<People>()
    .HasMany(x => x.dogs)
    .WithMany(y => y.persons)
    .Map(m =>
    {
        m.ToTable("PeoplesDogs");
        m.MapLeftKey("PeopleId");
        m.MapRightKey("DogId");
    });
于 2012-05-17T11:05:11.723 に答える