且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-22 10:58:12

在查询数据关闭的代理创建之前,使用此

  context.ContextOptions.ProxyCreationEnabled = FALSE; 



我想这可能是也EDMX设计全球关闭。



更新:



这适用于的ObjectContext 。随着的DbContext 的代码是:



  context.Configuration.ProxyCreationEnabled = FALSE ; 



再加上我看不出在EDMX设计师


的任何选项

In Entity Framework 4 Is it possible to choose to load some queries into a POCO without it using proxy classes? (For the purpose of caching that object for future read only use). I am using the Repository - Service pattern.

By this I mean:

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

What I want is for the order.Customer to actually use the POCO type MyApp.Models.Entities.Customer instead of a proxy to that type.

EDIT: Based on Ladislav's suggestion to add a "GetUnproxied" method to the Repository, I've made this change:

// 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;
}

Is this correct?

It does not look thread safe to me. Both methods use the same ObjectContext instance, so it might be possible for ProxyCreationEnabled == false to happen on one thread and then public IQueryable<T> GetQuery() to be called on another thread - which would suddenly mean that the proxy method could return the non proxied object.

Use this before you query data to turn off proxy creation

context.ContextOptions.ProxyCreationEnabled = false;

I think it can be also turned off globally in EDMX designer.

Update:

This applied to ObjectContext. With DbContext the code is:

context.Configuration.ProxyCreationEnabled = false;

plus I do not see any option in the edmx designer