EF Core – Code First with existing database ASP.NET Core

EFCore

In ASP.NET Core using a Entity Framework Core we only have the option to connect with a database by aproach code first. Edmx and Dbml will not be supported anymore.
So what to do if we have existing database and we want to create a model based on EF Core in application.

I’ll show you in a short tutorial how to get it with the easiest way.

Example

At the first we need to create class which is a reflection of the property in the database table.

tableDb

Then we need to create a class that will inherit from DbContext from the namespace EntityFrameworkCore and it will contain the properties of our table / tables.

Configure a connection to the database with a default connection string  from appsettings.json in the startup class.

Add migrations by use command Add-Migrations.

The following class was generated by migrations

We have to delete everything that is in the function „Up”. And use command Update-Database. After these operations, we have a generated migration and finally, we can „normally” use the code first approach without any conflicts.

example2

Link to the project.

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *