我在处理 Entity Framework 中的外键关系时遇到了问题。我有两个表:Persons和 Countries . Persons有一个指向 CountryId 的外键列.
作为 Countries表很少更改,我只想获取它的数据一次,处理 DatabaseContext , 并保留 Countries 的列表缓存在某处。这是我遇到问题的地方。
Entity Framework 似乎希望您打开数据库上下文,根据需要添加/编辑行,然后关闭数据库上下文。如果打开,获取数据,关闭;然后稍后打开,保存数据,关闭;它有麻烦。
所以我的 POCO 对象看起来像这样:
public class Country {
public int CountryId {get; set; }
public String Name {get; set; }
}
public Person {
public int PersonId {get; set; }
public virtual Country Country {get; set; }
}
然后,我试着创造一个这样的新人:
Country[] countries;
using (var dt = new DatabaseContext())
{
countries= dt.Countries.ToArray();
}
Person person = new Person();
person.Country = countries[0];
using (var dt = new DatabaseContext()) {
dt.Entities.Add(person);
dt.SaveChanges();
}
保存时, Entity Framework 在 Countries 中创建一个新行与 countries[0] 同名的表,而是一个新的递增 ID。这显然不是想要的结果——这个人应该有它的 Country_CountryId字段设置为 countries[0] 的 ID ,并且不应创建新行。
我该如何解决这个问题?我认为一种解决方案是强制 Entity Framework 在给定一个已经设置了主键的对象时不创建一个新行。有办法做到这一点吗?
请您参考如下方法:
我想知道您是否至少在 Internet 上进行了一些搜索,然后才投入大量精力来描述这个问题,因为这是每隔几天就会被问到的一个非常普遍的问题。
Add 方法添加实体图中的所有实体。因此,如果您将 country 连接到 person 并且 country 未附加到当前上下文,则在 上调用 会将 Add >personperson 和 country 标记为要插入的新实体。如果您不想插入 country,您必须告诉 EF country 不是新实体:
Person person = new Person();
person.Country = countries[0];
using (var dt = new DatabaseContext()) {
dt.Entities.Add(person);
dt.Entry(person.Country).State = EntityState.Modified;
dt.SaveChanges();
}
