This tutorial helps to create and update models from an existing database using Entity Framework Core. It explains about Scaffold-DbContext with its parameters like Connection, Provider, OutputDir, Force, Schemas, Tables, DataAnnotations.
Creating models and DBcontext classes from an existing database is called a Database First approach. For this tutorial, you will use .Net Core Class Library which we usually use for Data Access purpose.
Northwind is a sample relational database provided by Microsoft, we will be using it for this tutorial to create it's Entity Framework Core Models.
You can download Northwind database schema scripts here and execute it in SQL Server Management Studio(SSMS). This will create a new database with name the Northwind.
For this step, you will use .Net Core class Library as a separate project to handle Models and DBContext. Open your Visual Studio and follow below steps to create .Net Core Class Library. You can also have repository pattern with Web API
In this step, you will install the required NuGet packages to create models from existing SQL Server database. Click on Tools menu from Visual Studio -> NuGet Package Manager -> Package Manager Console. And execute below commands to install packages.
This will install latest stable nuget packages to EfCoreDBFirst .Net Core class library.
Entity FrameworkCore does not support visual designer or edmx. So Scaffold-DbContext is the command which will create entity and DBContext classes from an existing database. Scaffold-DbContext accepts different parameters along with the connection string of the database.
Create a new folder to place Entity and DBContext folder with name as Models -> DB.
Open Package Manager Console from Tools-> Nuget Package Manager -> Package Manager Console and execute below command.
Scaffold-DbContext "Data Source=(localdb)\ProjectsV13;Initial Catalog=Northwind; Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB
This creates entity classes for each table from the Northwind database and NorthwindContext class having virtual properties of tables to hold the table's data. Tables having the primary key will be generated.
Scaffold-DbContext generates NorthwindContext class which inherits from DbContext. This has an instance of DbContextOptions which carries information of configuration.
NorthwindContext.cs class has the OnConfiguring method to configure EF with Northwind database. and OnModelCreating having table relationships and constraints configured with Fluent API.
NorthwindContext has generated code as shown
namespace entity_framework_core_database_first_tutorial.Models.DB { public partial class NorthwindContext : DbContext { public NorthwindContext() { } public NorthwindContext(DbContextOptions<NorthwindContext> options) : base(options) { } public virtual DbSet<Categories> Categories { get; set; } public virtual DbSet<Customers> Customers { get; set; } //other table's virtual properties to hold their corresponding data protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Data Source=(localdb)\\ProjectsV13; Initial Catalog=Northwind;Integrated Security=True; Connect Timeout=30; Encrypt=False;TrustServerCertificate=False;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062"); modelBuilder.Entity<Categories>(entity => { entity.HasKey(e => e.CategoryId); entity.HasIndex(e => e.CategoryName) .HasName("CategoryName"); entity.Property(e => e.CategoryId).HasColumnName("CategoryID"); entity.Property(e => e.CategoryName) .IsRequired() .HasMaxLength(15); entity.Property(e => e.Description).HasColumnType("ntext"); entity.Property(e => e.Picture).HasColumnType("image"); }); //Other tables Fluent API configuration } } }
Notice OnConfiguring method from above code, the connection string is tightly coupled. you can not change it through config or appsettings file. You can implement this to configure your database connection string in the appsettings.json file.
You can use different parameters with Scaffold-DbContext to customize model creation from an existing database. Scaffold-DbContext accepts the below parameters.
Scaffold-DbContext "<connection string>" -Provider Microsoft.EntityFrameworkCore.SqlServer
Scaffold-DbContext "<connection string>" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB
Scaffold-DbContext "<connection string>" -OutputDir Models/DB -ContextDir Models/Context
Scaffold-DbContext "<connection string>" -Context NWContext
Scaffold-DbContext "<connection string>" -Schemas dbo, admin
Scaffold-DbContext "<connection string>" -Tables Categories, Products, Customers
Scaffold-DbContext "<connection string>" -Provider Microsoft.EntityFrameworkCore.SqlServer -DataAnnotations
Scaffold-DbContext "<connection string>" -Provider Microsoft.EntityFrameworkCore.SqlServer -Force
For updating models depending on the schema changes in database you can use -Force option to override and recreate models with the latest version of database schema.
Scaffold-DbContext "<connection string>" -Provider Microsoft.EntityFrameworkCore.SqlServer -Tables Customers, Orders, Products -Force
I found this tutorial particularly helpful. But if this is the Entity Framework Core Database First Tutorial where is the Second?