7

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

4

1 回答 1

17

在查询数据之前使用它来关闭代理创建

context.ContextOptions.ProxyCreationEnabled = false;

我认为它也可以在 EDMX 设计器中全局关闭。

更新:

这适用于ObjectContext. 代码DbContext是:

context.Configuration.ProxyCreationEnabled = false;

另外,我在 edmx 设计器中看不到任何选项

于 2011-07-13T22:51:46.727 回答