我一直把头发都撕了这么多天,在我完全秃顶之前,现在是时候让所有的人比我更聪明,怎么做。如何使用实体框架代码优先方法编辑实体?
我使用实体框架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