【问题标题】:Entity Framework 4.1 RC (Code First) - Entity not updating over associationEntity Framework 4.1 RC (Code First) - 实体不更新关联
【发布时间】:2011-03-31 23:26:41
【问题描述】:

我想要做的很简单。我有两个班级:

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<TownRecord> TownRecords {get; set; }
        }

当我想更新 TownRecord 类的 RecordType 属性时,我发现关联更新失败。不抛出异常但不执行更新:

 [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");
  }

注意:为了清楚起见,我删除了我的错误处理...

我看到一个与here 类似的问题,但我不明白。这可能是一个非常愚蠢的新手错误,但我已经 StackOverflowing 和谷歌搜索了几个小时,却一无所获。非常感谢任何帮助。

【问题讨论】:

  • 拉迪斯拉夫,谢谢。您的解决方案有效。由于一些验证,我仍然需要设置 RecordType 属性(tr.RecordType = new RecType),但它可以工作。抱歉,我错过了您的其他答案,但非常感谢您的指导!
  • 我投票结束这个问题,因为它是关于一个候选版本,也是一个过时的 EF 版本。

标签: c# entity-framework code-first entity-framework-4.1


【解决方案1】:

这不起作用,因为您使用的是独立关联。 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");
}

实际上,question with the same problem 是在您提出问题前 2 小时提出的。我还尝试提供与独立协会合作的解决方案,但我不喜欢它。问题是,对于独立关联,您需要附加 TownRecord 加载其实际的 TownRecordType 并将其替换为新的 TownRecordType

【讨论】:

  • 仍然,它应该像 OP 一样工作,不是吗?我有一个带有public virtual IList&lt;Suggestion&gt; Suggestions {get;set;}User 类和带有public virtual User User {get;set;}Suggestion 类;它无需显式标记 FK 关系即可工作,只需执行 user.Suggestions.Add(suggestion);...
猜你喜欢
  • 2023-04-02
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 2011-08-01
  • 1970-01-01
  • 2011-12-11
相关资源
最近更新 更多