Multi-Context InMemory Database

前端 未结 3 656
遇见更好的自我
遇见更好的自我 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:34

    Beside the same database name, the model must also be the same. This means that in case of an own implementation of IModelCacheKeyFactory, it's Create-Method must return "equal" objects.

    0 讨论(0)
  • 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<MyContext>(options =>
    {
        options.UseInMemoryDatabase("MyContext", InMemoryDatabaseRoot);
        options.UseInternalServiceProvider(serviceProvider);
     });
    
     services.AddDbContext<MySecondContext>(options =>
     {
        options.UseInMemoryDatabase("MyContext", InMemoryDatabaseRoot);
        options.UseInternalServiceProvider(serviceProvider);
      });
    

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

    0 讨论(0)
  • 2020-12-11 17:54

    The same name is enough. If your instances of DbContext do not 'see' the same in memory DB, it seems they use ones with different names. Make sure your DbContext is created once for the same name.

    EF Core 2.0 even re-uses in memory databases with the same name:

    In-memory databases must be named

    The global unnamed in-memory database has been removed and instead all in-memory databases must be named. For example:

    optionsBuilder.UseInMemoryDatabase("MyDatabase"); 
    

    This creates/uses a database with the name “MyDatabase”. If UseInMemoryDatabase is called again with the same name, then the same in-memory database will be used, allowing it to be shared by multiple context instances.

    0 讨论(0)
提交回复
热议问题