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

c# entity-framework


When I request the real entity class, the entity framework keeps returning proxies. When I execute my code for the first time, everything works as it should (no proxies), but on subsequent iterations, one of my DbSets always returns proxies rather than the true type.

I don't know why it works the first time and then doesn't the next time since I throw away the context after each loop.

This line of my code is broken. Although the Table property is set for all of my POCOs, there isn't any table attribute since it returns a proxy class.

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

Does the DbContext include any static magic that endures even after I delete the object?

I use the following to load my objects into memory:

MajorClasses = ctx.MajorClasses.ToArray();

Also, I attempted

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

I have the following set of instructions in my OnModelCreating

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

Accepted Answer

You may chooseObjectContext.ContextOptions.ProxyCreationEnabled to be false You won't be able to use some of EF's fancy capabilities, such as slow loading and, I think, change tracking, as a result.

Your program should be able to handle the proxies exactly like the kinds that they stand in for. Do you have a particular problem in mind?


The following checks are made to see whether the current type is a proxy because some code needs the POCO type rather than the proxy type.

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

Popular Answer

Use the following to disable proxy generation in Entity Framework 5:

_dbContext.Configuration.ProxyCreationEnabled = false;

Just set this attribute once before pulling data from the context.

Related Questions


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