Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.I’ve been recently migrating some existing EF6 code to EF Core. One aspect of EF Core I don’t often see is how testing with EF Core is drastically better than Entity Framework 6. There are two ways I’ve been handling running tests that use EF Core: Using In-Memory Provider and SQLite Provider but with SQLite In-Memory.
DbContextFirst thing I needed to do was have a constructor that took the OptionsBuilder that I could configure my DbContext options outside of the dbContext itself. This enables us to configure our context to use the InMemory Provider. During the OnConfiguring, check to see if the options have been configured, if not use our default setup. Here’s a snippet of what that looks like.
In-Memory ProviderMicrosoft provides the Microsoft.EntityFrameworkCore.InMemory NuGet Package that contains the In-Memory provider. With this package, we now can configure out DbContext to use an in-memory database.
GotchaOne thing to note is that if you are using transactions, the In-Memory provide does not support it. I’ve configured warnings to ignore these warnings. However, a deal breaker with using the In-Memory provider is if you use any relational database functionality in the DbContext. For example, if you are using
Database.ExecuteSqlCommandAsync or similar methods. These are not supported by the In-Memory provider since it cannot execute SQL.
SQLite In-MemoryTo work around the issue of needing to execute SQL, you may want to check out using the SQLite. Microsoft.EntityFrameworkCore.Sqlite package provides the provider and is similar to configure. However, you can configure SQLite connection to be in-memory. We also will need to make sure the schema is defined using the