【发布时间】:2015-09-03 18:33:54
【问题描述】:
为了解释这个问题,我有一个带有 Person 类的简单模型:
public class Person
{
public int Id { get; set; }
public virtual string Name { get; set; }
}
还有一个拥有 Person 集合的类 School:
public class School
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Person> Pupils { get; set; }
}
创建学校工作正常:
using (DatabaseContext ctx = new DatabaseContext())
{
Person p = new Person() { Name = "Thomas" };
Person p2 = new Person() { Name = "Markus" };
School s = new School();
s.Name = "Test";
s.Pupils = new ObservableCollection<Person>();
s.Pupils.Add(p);
s.Pupils.Add(p2);
ctx.Schools.Add(s);
ctx.SaveChanges();
}
并且在persons表中school_id外键设置正确:
Id Name School_Id
1 Thomas 1
2 Markus 1
但是当我尝试添加新瞳孔时:
using (DatabaseContext ctx = new DatabaseContext())
{
Person p = new Person() { Name = "Mark" };
s.Pupils.Add(p);
ctx.Persons.Add(p);
ctx.SaveChanges();
}
数据库表中 School_id 设置为空:
Id Name School_Id
1 Thomas 1
2 Markus 1
3 Mark null
我做错了什么?我知道我可以使用外键关联,但由于我计划将 Person Entity 与不同的相关实体一起使用,我更喜欢独立关联。
感谢您的帮助!!
【问题讨论】:
-
听起来
s没有附加到您应该拥有的上下文s = ctx.Set<School>().Where(x => x.Id == 1).First();。 -
tschmitt007 非常感谢。这就是问题所在。现在它起作用了。如果你写这个作为答案,我会标记它。
标签: c# entity-framework collections ef-code-first