Entity Framework Core Database First to Code Model

Many of us would be initially creating our model in one project and then migrate to database. What if you have another project, or a freelance project which needs the same model? You should not write all of the models again, right? Such scenarios where the Database exists and you need the models only (in your code) is called Database First Approach.

The following libraries are required to be installed for building your models in Entity Framework Core in a Database First Approach. The libraries/packages can be installed from Nuget Package Manager Console or the GUI in Visual Studio.

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.SqlServer.Design

Once you have installed the packages, run the following command to build your model from the database:

Scaffold-DbContext \"Server=<URL_For_Database_Server>;Database=<DB_Name>;user id=<UserId>;Password=<Password>;Trusted_Connection=True;\" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force

This would generate all of the models and the DB Context class as well. If it fails and results in the following error,

Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication.

then remove the Trusted_Connection=True from the above command.

Comments

Leave a Reply

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