Home > OS >  Migrate from EF to EF Core. Unloaded entity in the For Loop
Migrate from EF to EF Core. Unloaded entity in the For Loop

Time:02-03

We embark on a journey to migrate an existing EF4 project to EF7.

We stumbled upon a leak that will lead to many undetected bugs (no build errors).

In the EF4 project, we rely on Lazy Loading to get the data of related entities. For example:

var items = db.Items.GetXXXById(id);
var filteredItems = (from item in items 
                        where item.StatusId == 1
                        select item).ToList();
var childrens = from item in filteredItems
                where item.StatusId == 1
                from children in item.Childrens
                select children;

Debug.WriteLine(childrens.Count()); // This returned 0 on EF7 but the correct value on EF4.

The above code will return a correct value on EF4 but it returns zero on EF7.

To mitigate the above, we will have to add an "Include" to eager load the children. For example:

var items = db.Items.GetXXXById(id);
var filteredItems = (from item in items 
                        where item.StatusId == 1
                        select item).Include(i => i.Children).ToList();
var childrens = from item in filteredItems
                where item.StatusId == 1
                from children in item.Childrens
                select children;

Debug.WriteLine(childrens.Count()); // Both EF4 and EF7 returns the correct value.

But, without the build error thrown, we will have to check all our queries to figure out what we need to "Include". Is there a way or a tool that helps detect such "leak"?

CodePudding user response:

You can configure Lazy loading with proxies in your DbContext class like this:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);

This setting will work like EF4 that is lazy loading enabled by default.

IMHO, It's not a best practice for many circumstances. You should consider turn off lazy loading by default and taking care of the relationship between entities to avoid N 1 problem.

  • Related