我一直把頭髮都撕了這麼多天,在我完全禿頂之前,現在是時候讓所有的人比我更聰明,怎麼做。如何使用實體框架代碼優先方法編輯實體?
我使用實體框架4代碼首先CTP 5和MVC 3
異常消息,現在是「具有相同鍵的對象已經存在於ObjectStateManager該ObjectStateManager無法追蹤多個對象同一把鑰匙「。
一起來這裏的編輯表單發送到控制器:
public ActionResult Save(ClientEntity postedClient)
{
try
{
if (ModelState.IsValid)
{
Base.clientInterface.Save(postedClient);
return RedirectToAction("Index");
}
}
catch (Exception)
{
throw;
}
SetupManageData(null, postedClient);
return View("Manage");
}
客戶端界面上的保存方法是這樣的:
public void Save(ClientEntity theClient)
{
SetContext();
if (theClient.clientId == 0)
this.pContext.Clients.Add(theClient);
else
{
ClientEntity existingClient = GetSingle(theClient.clientId); // Get the existing entity from the data store.
// PseudoCode: Merge existingClient and theClient - Can this be done without using ObjectStateManager?
// PseudoCode: Attach merged entity to context so that SaveChanges will update it in the database - is this correct?
}
this.pContext.SaveChanges();
}
private void SetContext()
{
if (this.pContext == null)
this.pContext = new PersistanceContext();
}
持久化上下文是的DbContext,看起來像這樣:
public class PersistanceContext : DbContext
{
public DbSet<ClientEntity> Clients { get; set; }
}
我真的很想避免必須手動映射屬性,否則如果添加新屬性會有錯誤的空間。 – 2011-01-12 08:48:48