2012-03-27 43 views
16

我一直在使用數據庫優先的一部分,EF 4.1實體類型List`1是不是該機型爲當前上下文

我得到「的實體類型List`1不是模型的一部分當前的情況。「嘗試從我的編輯視圖更新記錄時出錯。

誤差以

db.Entry(properties).State = EntityState.Modified; 

這裏發生的是我的模型:

public class Users 
    { 
    [Key] 
    public int User_ID { get; set; } 
    public string UserName { get; set; } 

    [NotMapped] 
    public IEnumerable<App_Properties> User_Properties 
    { 
      get { return Properties.Where(u => u.User_ID == User_ID); } 
    } 

    public virtual ICollection<App_Properties> Properties { get; set; } 
} 

public class App_Properties 
{ 
    [Key] 
    public int Prop_ID { get; set; } 
    public int User_ID { get; set; } 
    public int App_ID { get; set; } 
    public string Key { get; set; } 
    public string Value { get; set; } 
    public DateTime DateEntered { get; set; } 
    public DateTime DateModified { get; set; } 

    [ForeignKey("User_ID")] 
    public virtual Users Users { get; set; } 
} 

這裏是我的控制器:

[HttpPost] 
public ActionResult Edit(ICollection<App_Properties> properties) 
{ 
    if (ModelState.IsValid) 
    { 
      foreach (var item in properties) 
      { 
       db.Entry(properties).State = EntityState.Modified; 
      } 

      db.SaveChanges(); 

      return RedirectToAction("Index"); 
    } 

    return View(properties); 
} 

我懷疑foreach循環不設置合適ICollection中每個項目的EntityState。

任何援助將不勝感激。

+1

快速語義記,名稱App_Properties.Users將意味着多個用戶,而不是一個。約定往往是一個單一的對象有一個單獨的名稱,因爲'var users = new Users()'意味着一羣人,而不是一個單一的項目。 – Leniency 2012-03-27 19:53:40

+0

是的,謝謝......我沒有控制數據庫,我讓表格的不正確命名傳播到我的代碼中。 – 2012-03-27 22:17:10

+0

雖然數據庫名稱不必 - 很容易改變你的POCO映射到實際的數據庫表OnModelCreating:'modelBuilder.Entity ().ToTable(「Users」)''。然後在Users類上進行簡單的F2重命名,然後將重命名傳播到您的項目中。與屬性名稱相同 - 您可以自定義它的任何地圖。 http://weblogs.asp.net/scottgu/archive/2010/07/23/entity-framework-4-code-first-custom-database-schema-mapping.aspx – Leniency 2012-03-28 01:16:05

回答

41

試着改變你的循環中:

foreach (var item in properties) 
{ 
    db.Entry(item).State = EntityState.Modified; 
} 

你分別致電db.Entry(properties),所以你試圖同時附加全收。 DbContext.Entry(對象)expects a single object,不是一個集合。

+1

謝謝..這擺脫了那個錯誤,但在對象狀態管理器錯誤中已經存在「具有相同密鑰的對象」。我能夠從http://stackoverflow.com/questions/8254854/object-with-same-key-already-exists-in-objectstatemanager獲得有關該錯誤的幫助。 – 2012-03-27 21:00:55

+0

謝謝...這是有幫助的 – 2016-11-18 10:12:29

8

非常感謝Leniency的回答。工作很好。

對於它的價值,我寧願保持在同一行我EntityState.Modified分配(如我的倍數),所以用下面的LINQ:

properties.ForEach(p => db.Entry(p).State = EntityState.Modified); 
相關問題