Entity Framework DB First

 

  • Create a Project of Type Class Library with the name EFDBFirst.Data
  • Add following Nuget Packages
  • Microsoft.EntityFrameworkCore (6.0.6 or latest stable package)
  • Microsoft.EntityFrameworkCore.SQLServer (6.0.6 or latest stable package)
  • Microsoft.EntityFrameworkCore.Tools (6.0.6 or latest stable package)
  • Microsoft.EntityFrameworkCore.Design(6.0.6 or latest stable package)
  • Create a New Database with the name DBFirst and Add 2 tables Employee and EmployeeEducation with 1 to many relationship
  • Run the following commands in package manager console
Scaffold-DbContext "Server=KELLGGNLPTP1078\SQLEXPRESS;Database=DBFirst;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

  • This command will generate the DB context class and model for all table. After this the process remains same as code First Approach
  • If we make any changes in DB tables and wanted to update our code then we need to run Scaffold-DbContext command with -force flag

Scaffold-DbContext "Server=KELLGGNLPTP1078\SQLEXPRESS;Database=DBFirst;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  -force

Reference Link: https://www.entityframeworktutorial.net/efcore/create-model-for-existing-database-in-ef-core.aspx

Source Code Linkhttps://github.com/kumarabhimanyu/EFDBFirst

Comments

Popular posts from this blog

Publish .Net Core Web API to Linux Host

Entity Relationship Using EF Core Code First Approach

Web API Using EF Core