Multi-Context InMemory Database

前端 未结 3 658
遇见更好的自我
遇见更好的自我 2020-12-11 17:21

Is it possible to have an InMemory database (ASP.NET Core) that is shared across multiple DbContexts? It seems that each DbContext type keeps its own database, even when the

3条回答
  •  爱一瞬间的悲伤
    2020-12-11 17:44

    This is possible nowadays, but indeed passing just the name is not enough if you use different context types. I'm using .net core 2.2 and had the exact same issue. My code now is now like this:

    I create a InMemoryDatabaseRoot object like this in class level

    private static readonly InMemoryDatabaseRoot InMemoryDatabaseRoot = new InMemoryDatabaseRoot();
    

    When I add the db contextes I pass the root instance

    services.AddDbContext(options =>
    {
        options.UseInMemoryDatabase("MyContext", InMemoryDatabaseRoot);
        options.UseInternalServiceProvider(serviceProvider);
     });
    
     services.AddDbContext(options =>
     {
        options.UseInMemoryDatabase("MyContext", InMemoryDatabaseRoot);
        options.UseInternalServiceProvider(serviceProvider);
      });
    

    I found it in a discussion here: https://github.com/aspnet/EntityFrameworkCore/issues/9613#issuecomment-430722420

提交回复
热议问题