多上下文内存数据库 [英] Multi-Context InMemory Database

查看:63
本文介绍了多上下文内存数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在多个DbContext之间共享一个InMemory数据库(ASP.NET Core)?似乎每个DbContext类型都保留自己的数据库,即使在UseInMemoryDatabase中指定了相同的数据库名称也是如此.

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.

推荐答案

如今这是可行的,但是如果您使用其他上下文类型,仅传递名称确实是不够的.我正在使用.net core 2.2,并且出现了完全相同的问题.我的代码现在是这样的:

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:

我在类级别创建了一个这样的InMemoryDatabaseRoot对象

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);
  });

我在这里的讨论中找到了它: https://github.com/aspnet/EntityFrameworkCore/issues/9613#issuecomment-430722420

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

这篇关于多上下文内存数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆