Entity Framework Core Scaffold-DbContext in separate Data and Entity Projects

Navin Singhwane
3 min readDec 11, 2020

In the practical scenario in that Project Solution may have different layers to manage and perform defined operations. In common structure of application can have Data Layer and Entity Layer separately.

For example, below is the application solution structure. Which have Data Layer, Entity Layer and Presentation Layer.

Solution Structure

Entity Framework Core, with DB first (Database already available) approach, generates code for a DbContext and Entities for a selected database.

In Visual Studio’s Package Manager Console, by Scaffold-DbContext command, to generate an entities and application DbContext in respective layers i.e. DbContext to be added into Data Layer and Entities to be created into Entity Layer Project.

To begin with this activity first we have to install dependent NuGet packages in Data Layer Project —

Make sure you have selected Default Project as below

Install-Package Microsoft.EntityFrameworkCore.Design

After package installation run following command for Scaffold-DbContext

Scaffold-DbContext “Data Source=DBSERVER;Initial Catalog=DBNAME;Integrated Security=True;” Microsoft.EntityFrameworkCore.SqlServer -Context “ExploreTechDbContext” -DataAnnotations -verbose -force -OutputDir “F:\ExploreTech.Entity” -ContextDir “F:\ExploreTech.Data”

  • ContextDir — is the path of Data Layer Project where DbContext to be generated.
  • OutputDir —is the path of Entity Layer Project where all entities files to be generated.

After successful run Scaffold-DbContext you can see the respective files are added in respective layers.

During this activity you may face other errors also for that Package Manager Console doesn’t provide much information to troubleshoot.

Below are few of them —

  • Build Failed

Problem & resolution — your solution may have compilation error; you need to resolve the same and make sure it is compiled successfully.

  • Instance Failure

Problem & resolution — check connection string which is not accurate in this case; you need to resolve the same.

For more details for and reference —

EF Core tools reference (Package Manager Console) — EF Core | Microsoft Docs

Thank You!

--

--