Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 450
user1147862 Avatar asked Oct 17 '18 06:10

user1147862


People also ask

What is the difference between DbContext and DbSet?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.

Should DbContext be in a using?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.

What is my DbContext?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.


1 Answers

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.

like image 59
Ivan Stoev Avatar answered Oct 10 '22 01:10

Ivan Stoev