How to disable eager loading when using InMemoryDatabase

entity-framework entity-framework-core

Question

I have an EF.Core 2.1 DataContext which I have not enable lazy loading for.

My configuration looks like this:

services.AddDbContext<DataContext>(options =>  
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

My tests use the same DataContext but use different options like so:

options.UseInMemoryDatabase(databaseName: "ProjectSpecs")

This is all working fine except that my in memory DataContext is eager loading everything.

If I ask for an entity is it loading all the related objects.

This means if I want to actually load a related property and forget to do so, my tests are passing as the related entity is loaded. But in the real application it is failing due to the .include being forgotten.

Can I make the in memory DataContext behave the same as the real one?

1
3
10/10/2018 12:47:57 PM

Popular Answer

I was suffering from the same issue and after reading a bunch of articles on the subject I came to the conclusion that the problem is really because the code-under-test is reading from the ChangeTracker where the test code has already assembled the object graph. Armed with that knowledge, I took my DbContext and overrode the SaveChanges method as shown below.

public override int SaveChanges()
{
    var affectedRows = base.SaveChanges();

    if (Database.ProviderName == "Microsoft.EntityFrameworkCore.InMemory")
    {
        ChangeTracker.Entries()
            .Where(e => e.Entity != null)
            .ToList()
            .ForEach(e => e.State = EntityState.Detached);
    }

    return affectedRows;
}

By detaching every object in the ChangeTracker it forces the code-under-test to go back to the database instead of pulling the existing object graph from the ChangeTracker.

3
2/1/2019 10:04:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow