How do I test whether a DbContext is in memory?

entity-framework entity-framework-core entity-framework-core-2.1

Question

I use .Net Core 2.1. My application uses Entity Framework Core, with a context CoreDbContext that derives from DbContext.

For unit testing, I use an in memory version of CoreDbContext, resulting in this code in my Startup.cs:

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

I also have methods that access the database via the context. These sometimes need to know whether the context is in memory or not, because an in memory context behaves differently from a normal one:

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

}

How can I test whether a context is in memory or associated with a real SQL Server database?

1
5
10/17/2018 8:23:47 AM

Accepted Answer

Every EF Core database provider adds extension method to the DatabaseFacade class which can be used to detect the configured provider for the context.

For SQL Server it's called IsSqlServer(), for MySQL - IsMySql(), for SQLite - IsSqlite() etc. And for in memory - not surprisingly IsInMemory() :)

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

The only tricky part is that since these are extension methods, the project must have reference to the corresponding package.

9
10/24/2018 12:27:41 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow