Why does Entity Framework return a proxy class rather than the underlying entity?

c# entity-framework

Question

I'm having trouble with entity framework returning Proxies when I want the actual entity class. The first time I run my code everything runs properly (no proxies), but every iteration afterwards one of my DbSets always returns proxies instead of the actual type.

I dispose of the context after every iteration, so I don't understand why the first time through it works, and every time after doesn't.

My code fails on this line. All my POCOs have the Table attribute set, but because it is returning a proxy class there is no table attribute.

TableAttribute attrib = (TableAttribute)attributes.Single();

Is there some behind the scenes static magic in the DbContext that lives after I destroy the object?

I move my objects into memory using the following

MajorClasses = ctx.MajorClasses.ToArray();

I also tried

MajorClasses = ctx.MajorClasses.AsNoTracking().ToArray();

In my OnModelCreating I have the following set

base.Configuration.ProxyCreationEnabled = false;
            base.Configuration.LazyLoadingEnabled = false;
1
31
9/13/2017 4:00:51 PM

Accepted Answer

You can set ObjectContext.ContextOptions.ProxyCreationEnabled to false. This will prevent you from using some of EFs fancy features like lazy loading and I believe change tracking.

As far as your app cares, it should be able to treat the proxies just like the types they represent. Is there a specific issue you are having?

Edit

We have some code that requires the POCO type instead of the proxy type and we do the following to detect if the current type is a proxy.

if (entityType.BaseType != null && entityType.Namespace == "System.Data.Entity.DynamicProxies")
{
    entityType = entityType.BaseType;
}
47
2/29/2012 3:30:56 PM

Popular Answer

To turn off proxy creation in Entity Framework 5 you can use the following,

_dbContext.Configuration.ProxyCreationEnabled = false;

Simply set this property once before using the context to pull data.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow