Search code examples
c#entity-framework-coreasp.net-core-webapi.net-5db-first

How to create models in .NET 5 Web API using EF Core DB first approach


I am working on .NET 5 Web API in which I have several projects in one solution. One project is for only controllers, another one I have added as class library project for interfaces, third project is also class library project for models which I would need to create it from existing DB using EF core. Fourth project is again class library project where I will write data manipulation logic using EF core. As most of the online tutorials are using Code first approach so I am little bit stuck for my DB first approach. Since I am doing this 1st time. I have few questions.

  1. Are these projects structures right? If not please suggest ideal enterprise level solution design structure.
  2. I have added EF core related nuget packages in 3rd an 4th project. Now I want to create entities from existing DB tables. How I can create it to particular project. I am running a below command

Scaffold-DbContext "Server=.;Database=BookStore;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer

Its creating context classes in API project instead of DTO project. How can I create models in DTO project.

enter image description here

  1. I have few tables now. Going forward we will add new table, SPs in DB as per requirements. In that case how to refresh models without disturbing existing models and validations logic written for it.

Solution

  • Open the Package manager console and select DTO from the dropdown. Run the following command. Make sure your directory must be there to import models into

    Scaffold-DbContext "Server=.;Database=PalletPal_LicenseStore;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir YourModelDirectory -Force