如何测试DbContext是否在内存中?

use*_*862 4 entity-framework entity-framework-core entity-framework-core-2.1

我使用.Net Core 2.1.我的应用程序使用Entity Framework Core,并具有CoreDbContext从派生的上下文DbContext

对于单元测试,我使用的内存版本CoreDbContext,从而在我的代码中产生了此代码Startup.cs

if (useInMemoryDatabase)
{
    services.AddDbContext<CoreDbContext>(options => 
           options.UseInMemoryDatabase("dbname"));
}
else
{
    services
      .AddDbContext<CoreDbContext>(options => 
           options.UseSqlServer(DefaultDbConnectionString));
}
Run Code Online (Sandbox Code Playgroud)

我也有通过上下文访问数据库的方法。这些有时有时需要知道上下文是否在内存中,因为内存上下文的行为与普通上下文不同:

void AddRecordX(CoreDbContext context)
{
    bool contextIsInMemory = .....;

}
Run Code Online (Sandbox Code Playgroud)

如何测试上下文是在内存中还是与真实对象相关联SQL Server database

Iva*_*oev 8

每个EF Core数据库提供程序都将扩展方法添加到DatabaseFacade该类中,该扩展方法可用于检测上下文的已配置提供程序。

对于SQL Server,它称为IsSqlServer(),对于MySQL- IsMySql(),对于SQLite- IsSqlite()等等。对于内存,也就这样IsInMemory()

void AddRecordX(CoreDbContext context)
{
    bool contextIsInMemory = context.Database.IsInMemory();
}
Run Code Online (Sandbox Code Playgroud)

唯一棘手的部分是,由于这些是扩展方法,因此该项目必须引用相应的软件包。