在 Entity Framework 4 中,是否可以选择将一些查询加载到 POCO 中而不使用代理类? (为了缓存该对象以供将来只读使用)。我正在使用存储库-服务模式。
我的意思是:
var order = _orderService.GetById(1);
// after order is loaded then we can see in the debugger that:
// order.Customer is of type System.Data.Entity.DynamicProxy.Customer_17631AJG_etc
我想要的是order.Customer
实际使用 POCO 类型MyApp.Models.Entities.Customer
而不是该类型的代理。
编辑:根据 Ladislav 向存储库添加“GetUnproxied”方法的建议,我进行了以下更改:
// this is the current method that must return a DynamicProxy
public IQueryable<T> GetQuery()
{
return ObjectSet.AsQueryable();
}
// this is the new additional method that must return the plain POCO
public IQueryable<T> GetReadOnly()
{
ObjectContext.ContextOptions.ProxyCreationEnabled = false;
var readOnly = ObjectSet.AsQueryable();
ObjectContext.ContextOptions.ProxyCreationEnabled = true;
return readOnly;
}
它是否正确?
对我来说它看起来线程不安全。两种方法都使用相同的 ObjectContext 实例,因此可能ProxyCreationEnabled == false
发生在一个线程上,然后public IQueryable<T> GetQuery()
在另一个线程上调用 - 这突然意味着代理方法可以返回非代理对象。
在查询数据之前使用此命令来关闭代理创建
context.ContextOptions.ProxyCreationEnabled = false;
我认为它也可以在 EDMX 设计器中全局关闭。
Update:
这适用于ObjectContext
. With DbContext
代码是:
context.Configuration.ProxyCreationEnabled = false;
另外我在 edmx 设计器中没有看到任何选项
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)