Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

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

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...