如何克隆POCO实体并添加到上下文

我正在使用EF4,我已经使用我的数据库结构中的代理创建了POCO对象。 我有一个POCO(对象),它与其他实体有很多关系。

我使用DataContractSerializer和BinaryFormatter创建了对象的深层副本,并将其称为clonedObject。

用于克隆的函数是:

public T CloneProxy(T source) { var dcs = new System.Runtime.Serialization .DataContractSerializer(typeof(T)); string filePath = "Initiative.txt"; using (FileStream file = new FileStream(filePath, FileMode.Create)) { (new BinaryFormatter()).Serialize(file, source); } context.CreateProxyTypes(new Type[] { typeof(Initiative) }); using (FileStream file = new FileStream(filePath, FileMode.Open)) { return (T)(new BinaryFormatter()).Deserialize(file); } } 

现在我有了clonedObject,如何将其添加到上下文中? 如何将其添加到数据库?

我的目标(只是给你一个关于POCO倡议的想法):

 Initiative { InitI InitName Comments } Comments { CommentI InitI } 

以下是我所做的一些方法以及我收到的错误。

 cloneInit.InitI = 0; Data_Business.RQRMComment[] arr = new Data_Business.RQRMComment[1]; arr = cloneInit.RQRMComments.ToArray(); for (int x = 0; x < arr.Length; x++) //each (var x in cloneInit.RQRMComments) { RQRMComment thisC = arr[x]; int y = thisC.InitI; thisC.InitI = 0; thisC.ID = 0; } Context.AddObject("Initiatives", cloneInit); Context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave); 

错误:

ex = {“无法添加或附加对象,因为其EntityReference的EntityKey属性值与此对象的EntityKey不匹配。”}

请帮忙,我花了太多时间在这上面。 谢谢。

我需要克隆我的实体,以便在表单上重新显示数据,以便用户可以选择“创建和添加类似”,以减少用户需要按顺序花费的工作量向我的数据库添加一系列类似的项目。

我检查了一些选项,包括reflection和序列化但是它们对于我想要实现的东西很乱,然后我发现我可以克服“XYZ是对象的关键信息的一部分并且无法修改”问题 – 即设置我的实体插入后的主键为0(保存更改) – 使用以下代码:

 MyDbEntities bb = new MyDbEntities(); //Add & Save new entry db.Product.AddObject(product); db.SaveChanges(); //Reset entity db.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Added); product.ProductId = 0;