C# 在 EF 中永久禁用 Configuration.ProxyCreationEnabled?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12868996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Permanently disable Configuration.ProxyCreationEnabled in EF?
提问by jwrightmail
Instead of having to do the following on every query, is there a way to just set that value globally? There is a lazyloading setting in the model view, but there does not seem to be a setting for the ProxyCreation.
不必对每个查询都执行以下操作,有没有办法全局设置该值?模型视图中有一个延迟加载设置,但似乎没有 ProxyCreation 的设置。
using (var context = new LabEntities())
{
**context.Configuration.ProxyCreationEnabled = false;**
var Query = from s in context.EAssets
.Include("Server").Include("Type").Include("Type.Definition")
where (s.Type.Definition.b_IsScannable == true) &&
(s.Server.s_Domain == Environment.UserDomainName || s.Server.s_Domain == null)
select s;
var Entities = Query.ToList();
}
I don't fully understand the benefits of this option, but i know that in visual studio is tags all my objects with gibberish serial suffixes and makes using the debugger unreasonable.
我不完全理解这个选项的好处,但我知道在 Visual Studio 中用乱码序列后缀标记我的所有对象,并使使用调试器变得不合理。
采纳答案by Mark Oreta
You can disable it in the constructor, so that it gets disabled anytime you create a new context:
您可以在构造函数中禁用它,以便在您创建新上下文时禁用它:
public class LabEntities : DbContext
{
public LabEntities()
{
Configuration.ProxyCreationEnabled = false;
}
}
回答by Scott Nelson
If you're using a model-first approach, meaning you have a .edmx file, the way to permanently disable this option is to modify the .Context.tt file. This file is a code generation template that the build process uses to generate your DbContext-derived class.
如果您使用的是模型优先方法,这意味着您有一个 .edmx 文件,则永久禁用此选项的方法是修改 .Context.tt 文件。此文件是构建过程用于生成 DbContext 派生类的代码生成模板。
Open this file and locate the constructor:
打开此文件并找到构造函数:
public <#=Code.Escape(container)#>()
: base("name=<#=container.Name#>")
{
<#
WriteLazyLoadingEnabled(container);
#>
//add the following line of code
this.Configuration.ProxyCreationEnabled = false;
}
then add the line of code to set this property to false. Rebuild your project and verify the generated context contains the line.
然后添加代码行以将此属性设置为 false。重建您的项目并验证生成的上下文包含该行。

