【发布时间】:2011-04-25 10:54:29
【问题描述】:
我正在使用 EF4,并且我已经使用我的数据库结构中的代理创建了 POCO 对象。我有一个 POCO(对象),它与其他实体有很多关系。
我使用 DataContractSerializer 和 BinaryFormatter 创建了一个对象的深层副本,我们称之为 clonedObject。
用于克隆的函数是:
public T CloneProxy<T>(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);
}
}
现在我已经克隆了对象,如何将它添加到上下文中?如何将其添加到数据库中?
我的对象(只是给你一个 POCO 倡议的想法):
Initiative
{
InitI
InitName
<collection>Comments
}
Comments
{
CommentI
<FK>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 不匹配。"}
请帮忙,我在这上面花了太多时间。谢谢。
【问题讨论】:
-
请不要走序列化路线,除非您确切知道自己在做什么,根据经验我知道这需要对您生成的代码进行大量修改才能使其正常工作。
标签: c# entity-framework entity-framework-4 clone poco