Multi-Context InMemory Database

点点圈 提交于 2019-12-30 18:53:13

问题


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 same database name is specified in UseInMemoryDatabase.


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/48437528/multi-context-inmemory-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!