entity-frameworkentity-framework-coreentity-framework-core-2.1

How do I test whether a DbContext is in memory?


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?


Solution

  • 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.