从数据库加载没有代理类?

时间:2011-07-13 22:37:25

标签: c# entity-framework poco proxy-classes

在实体框架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() - 这突然意味着代理方法可以返回非代理对象。

1 个答案:

答案 0 :(得分:16)

在查询数据以关闭代理创建之前使用此选项

context.ContextOptions.ProxyCreationEnabled = false;

我认为它也可以在EDMX设计师的全球范围内关闭。

更新

这适用于ObjectContext。使用DbContext代码为:

context.Configuration.ProxyCreationEnabled = false;

加上我在edmx设计器中看不到任何选项

相关问题