EF Core 2.1 In memory DB not updating records



I'm using the in memory database provider for integration tests however I don't seem to be able to update a record. I've run the same code against a real SQL database and everything gets updated fine. Here is my test fixture code.

Test Fixture:

public class TestFixture<TStartup> : IDisposable
    private readonly TestServer _testServer;
    public HttpClient TestClient { get; }
    public IDatabaseService DbContext { get { return _testServer.Host.Services.GetService<DatabaseService>(); } }

    public TestFixture() : this(Path.Combine("src")) { }

protected TestFixture(string relativeTargetProjectPatentDir)
    Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Testing");

    var builder = new WebHostBuilder()
        .ConfigureServices(services =>
            services.AddDbContext<DatabaseService>(options =>

    _testServer = new TestServer(builder)
        BaseAddress = new Uri("http://localhost:5010")

    TestClient = _testServer.CreateClient();
    TestClient.BaseAddress = _testServer.BaseAddress;

    public void Dispose()

I've spent most of the day googling this and not come across any other people talking about it so I'm assuming its probably my issue rather than a EF bug. I'm sure someone would have noticed a DB that you can't update.

5/25/2018 2:02:00 PM

Accepted Answer

It turned out that changing the lifetime of my DbContext in my test fixture to singleton solved my issue.

6/28/2018 2:38:34 PM

Popular Answer

Well it can be that DbContext is used in wrong way. I had the same problem. I used the DbContext in same way as you. I simply returned the instance by .Host.Services.GetService<TContext>. The problem with this approach is that DbContext will never release tracked entities so either you set entity State as EntityState.Detached and you force DbContext to reload it, or you will use scopes.

using (var scope = _testServer.Host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
  var dbContext = scope.ServiceProvider.GetRequiredService<DatabaseService>();
  //make any operations on dbContext only in scope

Related Questions


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