2011-03-31 106 views
1

我想要做的事情非常简单。我有两个类:实体框架4.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<TownRecord> TownRecords {get; set; } 
     } 

当我想以更新TownRecord类的记录类型的财产,我发现,该协会无法更新。不会抛出异常,但不执行更新:

[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和谷歌搜索了几个小时,并没有取得任何进展。任何帮助是极大的赞赏。

+0

拉迪斯拉夫,谢谢。你的解决方案工作。我仍然需要设置RecordType属性(tr.RecordType = new RecType),因为有一些验证,但它有效。对不起,我错过了您的其他答案,但非常感谢您的指导! – 2011-04-01 12:26:13

+0

[Entity Framework Code First - 为什么我不能以这种方式更新复杂属性?](http://stackoverflow.com/questions/5506116/entity-framework-code-first-why-cant-i-update -complex-properties-this-way) – MikroDel 2013-07-31 12:25:24

回答

2

这不起作用,因为您正在使用独立关联。 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替换它。

+0

不过,它应该像OP一样工作,它应该不是吗?我有一个'用户'类,其中包含'公共虚拟IList 建议{get; set;}'和'Suggestion'类,其中包含一个'public virtual User User {get; set;}';它不需要显式地标记FK关系,只需要执行'user.Suggestions.Add(suggestion);'...... – 2011-04-01 11:28:21

相关问题