1

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

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

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

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

4

1 回答 1

2

这不起作用,因为您使用的是独立关联。TownRecord和之间的关系TownRecordType不是城镇记录条目的一部分,因此将状态更改为已修改并没有说明关系状态。这就是“独立”的真正含义——它有自己的条目,但由于未知原因,很难在 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并用 new 替换它TownRecordType

于 2011-04-01T05:42:20.757 回答