我有如下代码。
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();
}
一切正常,但如果我插入下面的记录,学生记录将不会插入数据库。
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();
}
任何人都可以帮忙吗?