Why does disabling lazy loading cause related tabl

2019-07-12 16:37发布

问题:

Given:

        public SomeEntity Read(int primaryKey)
        {
            SomeEntity myEntity;
            using (var context = new MyEntities2())
            {
                context.Configuration.LazyLoadingEnabled = false;//This line is wacky
                myEntity = context.SomeEntities.SingleOrDefault(ct => ct.PrimaryKey == primaryKey);                     
                if (myEntity == null)
                    return myEntity;

                //Force eager Load...
                var bypassDeferredExecution = myEntity.RelatedTable1.ToList();
                var bypassDeferredExecution2 = myEntity.RelatedTable2.ToList();
            }
            return myEntity;
        }

If I set LazyLoadingEnabled = false then myEntity.RelatedTable1.Count == 0.
Leave at the default LazyLoadingEnabled = true then myEntity.RelatedTable1.Count == 2.

My understanding is that Lazy Loading and Eager Loading are polar opposites. I forced eager loading. I expect my related table (a cross reference table) to have 2 results whether or not I use lazy loading. So in my mind these results make no sense.

Why does lazy loading impact my results?

回答1:

You have to use Include to eagerly load related entities:

myEntity = context.SomeEntities
                  .Include("RelatedTable1")
                  .Include("RelatedTable2")
                  .SingleOrDefault(ct => ct.PrimaryKey == primaryKey);

Setting Lazy Loading to false won't cause it happen automatically.



回答2:

If you are using lazy loading, then there needs to be a LINQ to Entities Include method call to identify the (foreign keyed) tables to eagerly load.



回答3:

Navigation property isn't query, it's enumerable collection. You have 2 ways to get it from DB: - Lazy loading (will be loaded on the first access to property) - Eager loading (will be loaded after executing main query if you add Include({propertyName} method

So, if you turned off lazy loading and don't add Include methods to the query each navigation property will be empty (empty collection or null value for single entities)

The following code should work for your case:

myEntity = context.SomeEntities
.Include("RelatedTable1")
.Include("RelatedTable2")
.SingleOrDefault(ct => ct.PrimaryKey == primaryKey);


回答4:

Lazy loading defers the initialization of an object until it is needed. In this case it will automatically execute a query to the DB to load the object requested.

Eager loading loads a specific set of related objects along with the objects that were explicitly requested in the query.

So in order to use Eager Loading you need to specify the related objects that you want to load.

In EF you can achieve this using the method Include from ObjectQuery.

context.Entity.Include("RelatedObject");