Question

What is the equivalent of EntityCollection.Load() in EF6? I'm currently reading a book for EF4 and in one of its sample, it calls a Load() method:

foreach (var contact in contacts)
{
    contact.Addresses.Load();
    Console.WriteLine(contact.Addresses.Count);
}

I'm using EF6 for testing and looking at the internet, this is what I found that works:

foreach (var contact in contacts)
{
    context.Entry(contact).Collection(c => c.Addresses).Load();
    Console.WriteLine(contact.Addresses.Count());
}

But if this is the equivalent, why is it so slow (very, very slow) compared to the first code when I ran the code using EF4? Both codes have LazyLoading disabled. I know there are probably better ways of coding to make it load faster but I'm just curious as to why the code for EF6 is significantly slower than that in EF4 (for this matter). Or is this not the equivalent code in EF6?

Was it helpful?

Solution

The closer equivalent is probably:

context.Configuration.AutoDetectChangesEnabled = false;
foreach (var contact in contacts)
{
    context.Entry(contact).Collection(c => c.Addresses).Load();
    Console.WriteLine(contact.Addresses.Count());
}

The .Entry method calls DetectChanges internally if AutoDetectChangesEnabled is set to true (which it is by default). Depending on the number of entities in the context and the number of contacts automatic change detection can be rather time consuming, especially if called many times in a loop. In EF 4 and ObjectContext there is no AutoDetectChangesEnabled flag and change detection isn't performed in so many EF methods as it is in the DbContext API when AutoDetectChangesEnabled is true.

Could you try if that improves the performance? It would interest me as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top