C# EntityFramework InMemory Database for Easy Testing/Prototyping and Project sharing.

We’ve all been there: create a new project for a client, create a database in some form, share the project and include some instructions on how to create the database for the project.

They get the project, it builds — which is great! — but then it comes down to constructing the database. They may not have an instance of the database system you used (MSSQL, MYSQL, MongoDB, etc), which means they won’t be able to run the project.

Fortunately for us and for them, this isn’t the end of the world; there are ways we can get around this issue.

Let’s take advantage of the EntityFramework InMemory feature. I’ve created a Razor Page .NET 5 project and installed the following NuGet packages:

Once these are installed, we can create a very basic database structure. Let’s first create the two tables we want to store:

Database/Tables/Movie.cs

Database/Tables/Genre.cs (this isn’t used, it’s just for demonstration)

We now need to create the actual “database”. We will create two DbSets, one for Movie and one for Genre. The DbSet class represents an entity set that can be used for the database operation, such as create, read, update, and delete (https://entityframework.net/ef-dbset).

Database/MovieContext.cs

Now let’s update our Startup.cs so we can setup DI (dependency injection) for our application. In our Startup.cs we will need to add a database context and use the “UseInMemoryDatabase” feature which comes from Microsoft.EntityFrameworkCore.InMemory NuGet package.

Startup.cs

Now let’s update our Index.cshtml code so we can gather our movies from the database and then display them on the page.

Pages/Index.cshtml

Pages/Index.cshtml.cs

And that’s about it! Now anyone you give this project to will be able to run it without a problem.

The database self populates on construction and is stored in memory. This does mean any changes you do in the web app I.E. add a new movie will be lost when you stop the application (add movie to database feature not implemented). But remember the InMemory feature is made for testing/prototyping.

If you just want to see the code in action you can download my code from GitHub here (you will need .NET 5 SDK installed): https://github.com/MrApproved/Medium_EFInMemoryDatabase

Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.

References

Repository: https://github.com/MrApproved/Medium_EFInMemoryDatabase
Image: https://www.pexels.com/photo/green-typewriter-with-white-typewriter-4065406/
https://www.entityframeworktutorial.net/what-is-entityframework.aspx
https://entityframeworkcore.com/providers-inmemory