2010-12-08 28 views
0

我嘗試做與實體框架4如下:ApplyCurrentValues似乎不工作

public void Update(Site entity) 
{ 
    using (db) 
    { 
     db.Sites.Attach(db.Sites.Single(s => s.Id == entity.Id)); 
     db.Sites.ApplyCurrentValues(entity); 
     db.SaveChanges(); 
    } 
} 

但是,當我嘗試更新通過此方法的網站,我得到一個錯誤,告訴我說:

datetime2數據類型 類型轉換爲日期時間數據類型導致 超出範圍值。 聲明已被終止。

而這是因爲原始站點出於某種原因未通過Attach()方法加載。

有人可以幫忙嗎?

/馬丁

+0

您不需要附加加載的實體。如果您使用的是相同的上下文,它已經連接。你確定你的當前值沒有用DateTime.MinValue覆蓋一些加載的值嗎? – 2010-12-08 08:33:13

+0

當我刪除Attach()部分時,出現以下錯誤:「ObjectStateManager中找不到與提供的對象的鍵匹配的鍵的對象。驗證提供的對象的鍵值是否與鍵值必須應用更改的對象。「所以我認爲實體不再處於ObjectState – 2010-12-08 19:12:49

回答

3

你並不需要「附加」你已經取回的東西(拉吉斯拉夫是正確的)。一旦你檢索到一個實體(例如SingleOrDefault),它就是「在圖中」(EF內存 - 所以它可以做樂觀併發)。

如果你試圖做一個UPDATE <和「實體」的通過爲新/超脫......

嘗試短線技術

public void Update(Site entity) 
{ 
    using (db) 
    { 
     var stub = new Site { Id = entity.Id }; // create stub with given key 
     db.Sites.Attach(stub); // stub is now in graph 
     db.Sites.ApplyCurrentValues(entity); // override graph (stub) with entity 
     db.SaveChanges(); 
    } 
} 

話雖這麼說,在您提供了一些其他問題(數據轉換)的錯誤。

您是否使用模型上的數據類型檢查了您傳遞的「日期」值?

0
public ActionResult Edit(int id, Client collection) 
{ 
    try 
    { 
     // make sure the rec is in the context 
     var rec = dbEntities.Clients.First(r => r.ClientID == id); 
     // update the rec in the context with the parm values 
     dbEntities.Clients.ApplyCurrentValues(collection);   
     // make the changes permanent 
     dbEntities.SaveChanges();         
     return RedirectToAction("Index"); 
    } 
    catch 
    { 
     return View(); 
    } 
}