实体对象:克隆和插入
我正在尝试克隆/复制实体对象并将其插入数据库。我正在使用实体框架。
我在这里和其他论坛上发现了几个类似的问题。虽然确切的问题,但没有一个解决方案对我有用。
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)
它给我空。
* 不过,我找不到解决方案,而是使用反射找到了解决方法。*
I am trying to clone/copy an entity object and insert it to the DB. I am using Entity Framework.
I found several similar question here and over other forums. Though the exact issue, None of the solution worked for me.
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()
This throws the following error:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I tried to check for existance of the object in object state manager.
DataBaseContext.Current.ObjectStateManager.GetObjectStateEntry(clonedApp)
It give me Null.
* Though, I couldnt find a solution, got to a workaround for the requirement using reflection.*
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此错误表示您的新对象的主键与旧对象的主键相同,如果您正在克隆行,则需要为克隆的行提供一个新的 PK
This error says that you have the same primary key for your new object as you did for your old one, if you are cloning rows, you will need a new PK for the cloned row