Why is EF returning a proxy class instead of the actual entity?

By default, EF uses Change Tracking and uses an in-memory cache of all entities. You can use different Merge Options when working with EF. By default, EF 4.1 is set to AppendOnly Merge Option. As I understand, this means that if you have already queried an entity, subsequent queries will get the entity from the cache (if there are no detected changes in the database). So you might be seeing the cached entity coming back.

In EF 4.1, you can use NoTracking Merge Option. This will go to the database for every call.


In EF 6.1.3 you can get the right type using

using (var context = new BloggingContext()) { 
    var blog = context.Blogs.Find(1); 
    var entityType = ObjectContext.GetObjectType(blog.GetType()); 
}

Note that if the type passed to GetObjectType is an instance of an entity type that is not a proxy type then the type of entity is still returned. This means you can always use this method to get the actual entity type without any other checking to see if the type is a proxy type or not.

From MSDN


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.


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