【发布时间】:2024-05-11 13:10:01
【问题描述】:
我正在尝试克隆/复制实体对象并将其插入数据库。我正在使用实体框架。
我在这里和其他论坛上发现了几个类似的问题。虽然是确切的问题,但没有一个解决方案对我有用。
Application orginalApp = new Application().GetById(origAppId);
Application clonedApp = orginalApp.Clone<Application>(); //uses DataContractSerializer
DataBaseContext.Current.Detach(orginalApp); // Current is a property which returns Database context which is stored in httpcontext.current.items
clonedApp.EntityKey = null; // tried with and without this
clonedApp.Application_Id = 0; // tried with and without this. This is the primary key
clonedApp.Application_Name += " (clone)";
clonedApp.Create(); //The usual Addobject and SaveChange()
这会引发以下错误:
ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。
我试图在对象状态管理器中检查对象是否存在。
DataBaseContext.Current.ObjectStateManager.GetObjectStateEntry(clonedApp)
它给我 Null。
* 虽然我找不到解决方案,但使用反射找到了解决该要求的方法。*
【问题讨论】:
-
我认为你至少应该告诉你使用什么框架,因为它不清楚。
-
哎哟。对不起。问题已编辑。我正在使用实体框架
-
我通过使用反射实现克隆解决了这个问题
标签: database entity-framework object entity clone