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
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?
Yes, lazy loading is enabled in the Entity Framework ORM too, it is on by default in Entity Framework, so if you want to enable lazy loading in Entity Framework, you don't need to do anything.
To disable lazy loading on a specific post or page, open the post or page, and in the “Cache Options” meta box, un-check the “LazyLoad for images” option. Don't forget to publish or update the post or page to save your changes.
Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.
Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
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.
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">
This creates the following setting in the ObjectContext constructor:
public MyEntitiesContext() : base("name=MyEntitiesContext", "MyEntitiesContext") { this.ContextOptions.LazyLoadingEnabled = false; OnContextCreated(); }
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, Right-Click EDMX then Properties.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With