在Entity Framework 4中默认禁用延迟加载 [英] Disable lazy loading by default in Entity Framework 4
问题描述
默认情况下,在EF4中启用延迟加载。至少在我的项目中,我可以看到
It seems that lazy loading is enabled by default in EF4. At least, in my project, I can see that the value of
dataContext.ContextOptions.LazyLoadingEnabled
默认为true。我不想懒加载,我不想写:
is true by default. I don't want lazy loading and I don't want to have to write:
dataContext.ContextOptions.LazyLoadingEnabled = false;
每次我得到一个新的上下文。那么有没有办法在整个项目中默认关闭它?
each time I get a new context. So is there a way to turn it off by default, say, across the whole project?
推荐答案
以下答案是指 Database-First 或 Model-First 工作流(在询问问题时,实体框架(版本<= 4.0)可用的两个工作流)。如果您使用代码优先工作流程(自EF版本= 4.1起可用),请继续执行ssmith的答案对这个问题的正确解决方案。
The following answer refers to Database-First or Model-First workflow (the only two workflows that were available with Entity Framework (version <= 4.0) when the question was asked). If you are using Code-First workflow (which is available since EF version >= 4.1) proceed to ssmith's answer to this question for a correct solution.
edmx文件在< ConceptualModel>
和< EntityContainer>
定义延迟加载的属性,您可以将懒惰加载通常为false:
The edmx file has in the <ConceptualModel>
and <EntityContainer>
definition an attribute for lazy loading where you can set lazy loading generally to false:
<EntityContainer Name="MyEntitiesContext" annotation:LazyLoadingEnabled="false">
这将在ObjectContext构造函数中创建以下设置:
This creates the following setting in the ObjectContext constructor:
public MyEntitiesContext() : base("name=MyEntitiesContext", "MyEntitiesContext")
{
this.ContextOptions.LazyLoadingEnabled = false;
OnContextCreated();
}
我的示例并不意味着生成的应该手动修改ObjectContext(或更新的EF版本中的
DbContext
)(这将被数据库中的每个模型更新覆盖,因为ctorx指出),但EDMX文件的 edmx:ConceptualModels
部分中的 EntityContainer
元素应通过添加注释:LazyLoadingEnabled =false
属性 - 可以在XML编辑器中手动设置,也可以在设计器表面的属性页面上使用此选项。 EDMX文件的这种修改将自动生成上下文类,并在构造函数中使用禁用的延迟加载选项,如上所示。当模型从数据库更新时,EDMX文件修改本身不会被覆盖。
My example is not meant that way that the generated ObjectContext
(or DbContext
in newer EF versions) should be edited manually (which would be overwritten with every model update from the database, as ctorx pointed out) but that the EntityContainer
element in the edmx:ConceptualModels
section of the EDMX file should be edited by adding the annotation:LazyLoadingEnabled="false"
attribute - either manually in an XML editor or on the properties page of the designer surface where this option is available as well. This modification of the EDMX file will automatically generate the context class with the disabled lazy loading option in the constructor like shown above. The EDMX file modification itself does not get overwritten when the model is updated from the database.
这篇关于在Entity Framework 4中默认禁用延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!