Skip to content

ASP.NET CORE Integration tests: Entity framework DB first

In this short blog post I want to show how useful EF DB first approach is when testing. While working with legacy project you might now have endpoints to set all data in DB for test, also validating exact data in DB get easier.

Generate code from the database

Install two Nuget packages in a project that will contain DB files: Microsoft.EntityFrameworkCore.Design and Npgsql.EntityFrameworkCore.PostgreSQL don’t forget to rebuild the solution.

Next install dotnet-ef global tool and invoke it with following configuration. Tool has variety of configuration parameters, but for the sake of simplicity we will use only minimal set.

dotnet ef dbcontext scaffold "Server=127.0.0.1;Port=6444;Database=weather;User Id=admin_user;Password=secretPassword123!;" Npgsql.EntityFrameworkCore.PostgreSQL --output-dir Weather --no-onconfiguring --force

At this point we should have all necessary files to change dapper into EF.

Only a few changes are needed, create DataAccess inject database string, and use an entity framework in your project or tests. Source code is always available at GitHub

In memory

Why ? If someone is using EF code first on enterprise, please let me know how it’s going.

Summary

I find Entity Framework is really helpful in tests, you can easily add data to DB and validate if tests performed correct changes to DB. When the database changes, you only need to run generate.cmd script to update all code and if there are issues, they are in compile-time, which makes maintenance and updates easy.

Published inSoftware Development

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *