132
CHAPTER 5 | Designing and Developing Multi-Container and Microservice-Based .NET Applications
EF Core InMemory database versus SQL Server running as a container
Another good choice when running tests is to use the Entity Framework InMemory database provider.
You can specify that configuration in the ConfigureServices method of the Startup class in your Web
API project:
public
class
Startup
{
// Other Startup code ...
public
void
ConfigureServices
(IServiceCollection services)
{
services.
AddSingleton
(Configuration);
// DbContext using an InMemory database provider
services.
AddDbContext
(opt => opt.
UseInMemoryDatabase
());
//(Alternative: DbContext using a SQL Server provider
//services.AddDbContext(c =>
//{
// c.UseSqlServer(Configuration["ConnectionString"]);
//
//});
}
// Other Startup code ...
}
There is an important catch, though. The in-memory database does not support many constraints that
are specific to a particular database. For instance, you might add a unique index on a column in your
EF Core model and write a test against your in-memory database to check that it does not let you add
a duplicate value. But when you are using the in-memory database, you cannot handle unique indexes
on a column. Therefore, the in-memory database does not behave exactly the same as a real SQL
Server database
—
it does not emulate database-specific constraints.
Even so, an in-memory database is still useful for testing and prototyping. But if you want to create
accurate integration tests that take into account the behavior of a specific database implementation,
you need to use a real database like SQL Server. For that purpose, running SQL Server in a container is
a great choice and more accurate than the EF Core InMemory database provider.
Dostları ilə paylaş: