E.F Core – Existing Database

Hi everyone! Today, I want to talk about an interesting feature of E.F Core. Many times, we need to begin a project with an existing database and this isn’t the old school with Database first (I miss it 🙁 ) however we have tools with we can attack the problem 😉

Let’s code!

First step: Startup – New project

I need to create a project, in my case a Migration Console Project (Net Core).

startup project

The second step – Installing packages!

We need to interact with the database, in our case, we’ll interact with a SQL Server DB. For this reason, we need to install the NuGet package: Microsoft.EntityFrameworkCore.SqlServer.

installing Sql Server EF Core

Then, we need to install: Microsoft.entityframeworkcore.Design package NuGet too. This package has the logic to use Migrations and Reverse Engineering.

installing Design

Thirst step: Mapping tables!

Now, we work with the Package Nuget Console. If we go to E.F Documentation, we can see the following example:

PM> Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

This command will apply reverse engineering over every table in the database and it will create all models.
In this case, the entities will be in a Models folder (namespace projectName.Models)

We can specify which tables we want to migrate with the following command: -Tables. For example:

PM> Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models --Tables Table1,Table2,Table3

In our case, we will interact with a SQL DATABASE with login and we want to get all Tables. In addition, we want that every new class are in Entities namespace.

PM> Scaffold-DbContext "Server = DATABASE_SERVER_NAME; Database = BD_NAME; persist security info=True;user id=USER;password=PASSWORD;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities

Result:

We can see the new entities in our project and the DB Context!

Fourth step: Say Hello to the DB!

We use a using block to instantiate the CONTEXT and then we retrieve all categories from the DB.

That’s all!

Big hug!