Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
402 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

//using Microsoft.EntityFrameworkCore.Storage;
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...