我刚开始使用Entity Framework而不是我的普通NHiberante来看看EF是如何工作的,到目前为止我遇到了很多问题,但其中一个特别是分离一个对象并保留相关的子对象。
我买了O'Reilly实体框架书,它告诉你“默认情况下是实体框架在分离时不保留对象图”但它没有显示你如何保持图形!谢谢O'Reilly,这真的很有用。
无论如何,如果有人可以提供帮助,那将很棒,代码如下:
using (var creativeWorkshopEntities = new CreativeWorkshopEntities())
{
var q = from c in creativeWorkshopEntities.Job.Include("Files")
where c.Id == jobId
select c;
var job = q.First();
creativeWorkshopEntities.Detach(job);
return job;
}
谢谢!
丹
答案 0 :(得分:24)
请尝试使用NoTracking查询。这样就不会附加对象了,所以你不需要'拆分',这就是图表被粉碎的时候:
即
using (var creativeWorkshopEntities = new CreativeWorkshopEntities())
{
creativeWorkshopEntities.Job.MergeOption = MergeOption.NoTracking;
var q = from c in creativeWorkshopEntities.Job.Include("Files")
where c.Id == jobId
select c;
var job = q.First();
return job;
}
希望这有帮助
亚历
(项目经理实体框架小组)
答案 1 :(得分:3)
在EF5中,MergeOption不再处于DbSet级别。所以根据这个:http://msdn.microsoft.com/en-us/data/hh949853.aspx
如果您想进行不跟踪查询,则需要执行以下操作:
var q = from c in creativeWorkshopEntities.Job.AsNoTracking().Include("Files")
where c.Id == jobId
select c;
答案 2 :(得分:2)
查看http://www.codeproject.com/KB/architecture/attachobjectgraph.aspx
这是一个很棒的解决方案,可能会帮助您 - 请注意作者在他自己的博客上也有更新版本 - http://www.codetuning.net/blog/post/Entity-Framework-reattaching-entity-graphs-(3).aspx
保
答案 3 :(得分:0)
使用下面的代码将相关对象保存在内存中。
using (var creativeWorkshopEntities = new CreativeWorkshopEntities())
{
var q = from c in creativeWorkshopEntities.Job.Include("Files")
where c.Id == jobId
select c;
var job = q.First();
return (Job)Detach(job);
}
private Object Detach(Object object)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, dbo);
stream.Position = 0;
return formatter.Deserialize(stream);
}
}