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

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

问题描述

是否可以在多个 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

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

我在这里的讨论中找到了它: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

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

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