Entity Framework 4.1 RC (Code First) - Entity not updating over association

前端 未结 1 1444
耶瑟儿~
耶瑟儿~ 2021-01-24 16:34

What I\'m trying to do is fairly simple. I have two classes:

public class TownRecord
    {
        public int Id { get; set; }
        public string ShortName {         


        
相关标签:
1条回答
  • 2021-01-24 16:47

    This doesn't work because you are using independent association. Relation between TownRecord and TownRecordType is not part of town record's entry so changing state to modified doesn't say anything about state of relation. That is the real meaning of "independent" - it has its own entry but for unknown reason it is hard to get it in DbContext API (EF 4.1). Proposed way is using Foreign key association instead of independent association. To change your association to foreign key you must do this:

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

    You will change your code to:

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

    Actually the question with the same problem was asked 2 hours before you asked the question. I also tried to provide solution which works with independent association but I don't like it. The problem is that for independent association you need to have attached TownRecord loaded its actual TownRecordType and replace it with new TownRecordType.

    0 讨论(0)
提交回复
热议问题