2011-03-31 105 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

相關問題