entity framework4.1 RC(代码优先) – 实体不更新关联

我想做的事情很简单。 我有两节课:

public class TownRecord { public int Id { get; set; } public string ShortName { get; set; } public string FileName { get; set; } public string tags { get; set; } public virtual TownRecordType RecordType { get; set; } public DateTime? DateScanned { get; set; } public DateTime? RecordDate { get; set; } [StringLength(4000)] public string Comments { get; set; } public string UploadedBy { get; set; } } public class TownRecordType { public int Id { get; set; } public string RecordType { get; set; } public virtual ICollection TownRecords {get; set; } } 

当我想更新TownRecord类的RecordType属性时,我发现该关联无法更新。 不会抛出exception但不执行更新:

  [HttpPost] public ActionResult Edit(int id, TownRecord tr, FormCollection collection) { TownRecordType newRecType = _ctx.TownRecordTypes.Find(Int32.Parse(collection["RecordType"])); tr.RecordType = newRecType; _ctx.Entry(tr).State = EntityState.Modified; _ctx.SaveChanges(); return RedirectToAction("List"); } 

注意:为清楚起见,我删除了error handling…

我在这里看到了类似的问题,但我没有得到它。 这可能是一个非常愚蠢的新手错误,但我已经StackOverflowing和谷歌搜索几个小时,无处可去。 任何帮助是极大的赞赏。

这不起作用,因为您使用的是独立关联。 TownRecordTownRecordType之间的关系不是城镇记录条目的一部分,因此将状态更改为已修改状态并未说明关系状态。 这就是“独立”的真正含义 – 它有自己的条目,但由于未知原因,很难在DbContext API(EF 4.1)中获得它。 建议的方法是使用外键关联而不是独立关联。 要将关联更改为外键,您必须执行以下操作:

 public class TownRecord { public int Id { get; set; } ... [ForeignKey("RecordType")] public int RecordTypeId { get; set; } public virtual TownRecordType RecordType { get; set; } ... } 

您将代码更改为:

 [HttpPost] public ActionResult Edit(int id, TownRecord tr, FormCollection collection) { tr.RecordTypeId = Int32.Parse(collection["RecordType"]); _ctx.TownRecords.Attach(tr); _ctx.Entry(tr).State = EntityState.Modified; _ctx.SaveChanges(); return RedirectToAction("List"); } 

实际上,在您提出问题之前2小时,询问了具有相同问题的问题。 我也试图提供与独立协会合作的解决方案,但我不喜欢它。 问题是,对于独立关联,您需要附加TownRecord加载其实际的TownRecordType并将其替换为新的TownRecordType