在 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()
在另一个线程上调用 - 这突然意味着代理方法可以返回非代理对象。