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
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With