I have the code as below.
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>();
}
}
The context is
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);
}
}
If I insert the records likes below,
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();
}
everything works well, but if I insert the records likes below, the Student record will not insert into database.
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();
}
Anyone can help?
You can’t use the interface
IPeoplehere:Navigation properties must refer to entity classes – either abstract or concrete – of your model.
A possible alternative might be to use an abstract class
Peopleinstead of an interface. But you have to put the navigation property……into that abstract class, not into the derived
Studentclass, becauseDog.personsrefers to the abstract classPeople, something like:And the mapping would be: