我正在使用 Entity Framework 4.1(代码优先)开发一个小型示例项目。我的课程如下所示:
public class Context : DbContext
{
public IDbSet<Person> People { get; set; }
public IDbSet<EmployeeType> EmployeeTypes { get; set; }
}
public class Person
{
[Key]
public int Key { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
virtual public EmployeeType EmployeeType { get; set; }
}
public class EmployeeType
{
[Key]
public int Key { get; set; }
public string Text { get; set; }
virtual public ICollection<Person> People { get; set; }
}
我已经将几个 EmployeeTypes(“first”、“second”)保存到数据库中,并且我已经保存了一个拥有第一个类型的 Person。现在我想修改Person。我知道我可以通过加载 Person、更改属性然后保存来做到这一点。但是我想做的,在我看来它应该起作用的,是这样的:
var c = new Context();
var e = c.EmployeeTypes.Single(x => x.Text.Equals("second"));
var p = new Person {
Key = originalKey, // same key
FirstName = "NewFirst", // new first name
LastName = "NewLast", // new last name
EmployeeType = e }; // new employee type
c.Entry(p).State = EntityState.Modified;
c.SaveChanges();
奇怪的是,这会更改 FirstName 和 LastName,但不会更改 EmployeeType。如果我得到一个新的 Context 并请求这个 Person,EmployeeType 仍然设置为“first”,就像这段代码运行之前一样。
我需要做什么来更新导航属性,而不仅仅是标量属性? (这尤其令人费解,因为对于 EmployeeType,唯一真正需要更改的是 Person 表中的外键,而该键是一个标量属性。)
(顺便说一下,我知道我可以通过先检索 Person 来做到这一点,然后一个接一个地更改属性,但是当我在 ASP.NET MVC 中使用模型绑定时,似乎这种方式会更容易,因为我' 将在我的 POST 方法中已有更新的人员对象。)