为什么EF返回代理类而不是实际实体? [英] Why is EF returning a proxy class instead of the actual entity?

查看:46
本文介绍了为什么EF返回代理类而不是实际实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想要实际的实体类时,我在实体框架返回代理方面遇到麻烦。第一次运行代码时,所有程序都可以正常运行(没有代理),但是此后的每个DbSet中的每次迭代都始终返回代理而不是实际类型。

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.

我的代码在此行失败。我所有的POCO都设置了Table属性,但是因为它返回的是代理类,所以没有table属性。

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();

在DbContext中是否存在一些静态魔术,这些魔术在销毁对象后仍然存在?

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();

我也尝试过

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

在我的OnModelCreating中,我有以下设置

In my OnModelCreating I have the following set

base.Configuration.ProxyCreationEnabled = false;
            base.Configuration.LazyLoadingEnabled = false;


推荐答案

您可以设置 ObjectContext。 ContextOptions.ProxyCreationEnabled 设置为false。这将阻止您使用某些EF奇特功能,例如延迟加载和我相信更改跟踪。

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?

编辑

我们有一些特定问题吗?需要POCO类型而不是代理类型的代码,我们执行以下操作来检测当前类型是否是代理。

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

这篇关于为什么EF返回代理类而不是实际实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆