【发布时间】:2017-05-11 19:31:18
【问题描述】:
我正在尝试以 ASP.Net MVC 方式更新 EF6(代码优先)中的外键。
让我解释一下:
我的实体
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
我的数据库
表国家有 2 条记录:
- Id = 1,名称 = 法国
- Id = 2,名称 = 加拿大
表人有 1 条记录:
- Id = 1,名称 = Nicolas,Country_Id = 1
我的代码
// In a MVC application, these class has been retrieved via EF in a previous page. So now, we've lost all "proxy" informations
var p = new Person() { Id = 1, Name = "Nicolas" };
// Change country
p.Country = new Country() { Id = 2, Name = "Canada" };
// Persist all in DB
using (var db = new TestDbContext())
{
db.Persons.Attach(p); // Reattach to EF context
db.Entry<Person>(p).State = EntityState.Modified; // Flag modified state
db.SaveChanges(); // Generate only modification on field "name"
}
我的问题
执行前面的代码时,生成的 SQL 永远不会包含 person 表中的 country_Id 字段。
我的“不”问题
我知道在一个 EF 上下文中执行所有这些代码行时它可以完美运行,但在我的情况下,我将拥有来自我的 ASP.Net MVC 页面的数据。 我也想避免检索现有数据并逐个修改每个字段
【问题讨论】:
-
首先,它是
one-to-many关系。其次,如果您希望能够在修改中包含Country_Id而无需从数据库中加载数据,则在Person实体中提供显式Country_Id属性并设置它而不是导航属性。你可以在 SO 上找到这样的例子。 -
问题是,设置
State = EntityState.Modified不会将导航属性(关系)设置为已修改,只有标量属性。
标签: c# entity-framework-6 foreign-key-relationship