Preface
我知道这可能已经被视为疯狂的问题,但我正在寻找最有教养的建议和PROVEN关于如何进行复印的建议ALL来自某个实体的数据(即所有实体和关系)ObjectContext
到一个新创建的ObjectContext
在另一家商店支持。See 在实体框架中“克隆”EntityConnections 和 ObjectContext看看我是如何设置的。
Intro
我见过在实体框架上克隆数据, but:
我在找整个辣酱玉米饼馅,即整个对象图:所有实体和关系。稍后,我将对对象图的哪些部分进行更细粒度的选择)
根据我下面的更新,我还没有使序列化起作用,但仅在特殊情况下起作用。我觉得这确实是一项不那么复杂的任务,但它却具有惊人的挑战性。我确实需要一些关于如何使其发挥作用的见解。
Step 1
好的,这就是我到目前为止所尝试的。
我知道当我使用Detach
/Attach
权力二人组,关系已经崩溃——我实际上想保留整个对象图。
因此,我正在考虑使用以下命令加载根实体MergeOption.NoTracking
option:
var serializer = new DataContractSerializer(typeof(Root));
var query = (ObjectQuery<Root>) sourceContext.Roots
.Include(d => d.Children.Select(c => c.MoreChildren.Select(r => r.EvenMoreChildren)))
.Include(d => d.Children.Select(c => c.MoreChildren.Select(r => r.MoreAndMoreChildren)))
.Include(d => d.Children.Select(c => c.MoreChildren.Select(r => r.Shizzle)));
foreach (var d in query.Execute(MergeOption.NoTracking)) {
//sourceContext.Detach(d); // not needed
Print(d);
using (var ios = new MemoryStream()) {
serializer.WriteObject(ios, d);
ios.Seek(0, SeekOrigin.Begin);
var dd = (Root) serializer.ReadObject(ios);
//Console.WriteLine(string.Join(",", dd.EntityKey.EntityKeyValues.Select(k => k.Key + "=" + k.Value)));
targetContext.Roots.AddObject(dd);
}
}
鉴于我将实体加载为非跟踪,我不需要调用sourceContext.Detach(d)
不再了。
The Print
方法只是打印子对象树,它表明到目前为止一切进展顺利(我不会在这里显示它,因为它很大而且不相关)。
然而,现在整件事都在吹@serializer.WriteObject(ios, d)
并显示以下消息:
“当一个对象返回时NoTracking
合并选项,只有当EntityCollection
or EntityReference
不包含物体。”
(这有点道理,因为序列化器可能试图延迟加载相关实体。)
请记住,如果我不使用NoTracking
,我必须分离实体,但那样我就会失去我的关系......
Step 2
当然我尝试过设置sourceContext.ContextOptions.LazyLoadingEnabled = false
就在执行序列化循环之前,这修复了上面的错误,但这导致了臭名昭著的结果:
“无法添加或附加该对象,因为它EntityReference
has an EntityKey
属性值不匹配EntityKey
对于这个物体。”
另外,请记住我仍然无法取消注释sourceContext.Detach(d)
因为我加载了根NoTracking
...
Step 3
我尝试过设置EntityKey = null
在克隆实体的序列化之前,甚至在反序列化之后......一切都无济于事:
sourceContext.ContextOptions.LazyLoadingEnabled = false;
foreach (var d in query.Execute(MergeOption.NoTracking)) {
//sourceContext.Detach(d);
Print(d);
d.EntityKey = null;
using (var ios = new MemoryStream()) {
serializer.WriteObject(ios, d);
ios.Seek(0, SeekOrigin.Begin);
var dd = (Root) serializer.ReadObject(ios);
if (dd.EntityKey != null) {
Console.WriteLine("Deserialized EntityKey: {0}", string.Join(",", dd.EntityKey.EntityKeyValues.Select(k => k.Key + "=" + k.Value)));
dd.EntityKey = null;
}
targetContext.Roots.AddObject(dd);
}
}
可疑的是,我什至不知道上面所说的例外是什么该死的“对象”。
我真的、真的、真的、真的注定要尝试用纯粹的 EF 方法来解决这个问题吗???
我彻底完蛋了吗?!?!?! :(