私はこれについて何日も髪を引き裂いてきましたが、完全にハゲになる前に、私より賢いすべての人にこれを行う方法を尋ねる時が来ました.
Code First CTP 5 および MVC 3 で Entity Framework 4 を使用しています。
現在の例外メッセージは、「同じキーを持つオブジェクトが既に 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");
}
クライアント インターフェイスの Save メソッドは次のとおりです。
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; }
}