Alex Rivera | Logout

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

Asked 2012-02-29T15:03:02.960
38

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;
Edit
Report

1 Answer

2

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.

answered 2012-02-29T15:10:25.307

Your Answer