Updated April 1, 2023
Introduction to Entity Framework Core Database-First
Entity Framework Core Database-First is easy to build and is used to make the model from the database by commands of Scaffold-DbContext with the help of the provider as parameters and the connection string. Creating the Context Class and Entity Class from the existing database is called the Database-First approach; both classes are automatically created by Entity Framework from the database. So initially we have to create the database for Entity Framework Core first.
Overview of Entity Framework Core Database First
Entity Framework Core supports the Database-First approach through the Scaffold DbContext command. The Database-First approach is nothing but creating the models and the DbContext classes from an existing database, the both classes are automatically created by Entity Framework from the database. So initially we have to create the database for Entity Framework Core first.
We going to learn how to build the Context Class and Entity Class from an existing database in Entity Framework Core, creating both classes from an existing database is called the Database-First method. Entity Framework Core supports the Database-First approach through the Scaffold DbContext command through the PMC (Package Manager Console), those commands scaffold the Entity and DbContext Classes for the desired database.
Creating Database Entity Framework Core Database
The Database-First approach is nothing but creating the models and the DbContext classes from an existing database. Let’s see the creation of Database-First EF Core as follows,
Initially, we need to know about the requirement of the creation in EF Core Database-First, the creation requirements are
- We need the Visual Studio 2017 or the higher versions like EF Core 3.1 available in Visual Studio 2019.
- For the previous version, we need to make use of EF Core 2.2 in .NET Core SDK 2.2 and for the EF Core Version 3.1 in .NET Core SDK 3.0
- Use the latest version of NuGet Package Manager
- Use the latest version of Windows PowerShell.
Next to Create Database in SQL Server to work with Entity Framework Core, initially create the simple database in SQL Server and give the appropriate name and create the tables with Employee table and Department table as follows
Department Table
CREATE TABLE [dbo].[Department](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Employee Table
CREATE TABLE [dbo].[Employee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[Name] [varchar](100) NOT NULL,
[Designation] [varchar](25) NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
To create a new project OpenàVisual Studioà Fileà Newà Project in the new dialog box select the Visual C# à .Net Core on the left side and in the right side select Console App. Enter the project name and click OK.
To install NuGet Packages, once creating a new project we have to include the necessary packages,
Click on the Tools Menu à NuGet Package Manager à Package Manager Console.
If you have the EF Core Version 5 then execute the command in (PMC) Package Manager Console
install-Package Microsoft.EntityFrameworkCore.Tools
If you have the EF Core Version 3.1 then execute the command in (PMC) Package Manager Console
install-Package Microsoft.EntityFrameworkCore.Tools -Version 1.10
If you have the EF Core Version 2.2 then execute the command in (PMC) Package Manager Console
install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.6
If you have the EF Core Version 1.1 then execute the command in (PMC) Package Manager Console as follows,
install-Package Microsoft.EntityFrameworkCore.Tools -Version 1.5
Create classes from the Database
Now you run the CLI Scaffold Command on the Package Manager Console window. You can open this window from Tools ➤ NuGet Package Manager ➤ Package Manager Console in Visual Studio.
Here you can execute the CLI Scaffold Command in the PMC (Package Manager Console), just Open the Toolsà NuGet Package Managerà Package Manager Console in VS and enter the following commands to create the entity and context classes,
PM> dotnet ef dbcontext scaffold “Server=your serverName;Database=your db_name;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -o Models
Let’s see the entity classes are created as follows,
Employee.cs
using System;
using System.Collections.Generic;
namespace EF_DB_First.Models
{
public partial class Employee
{
public int Id { get; set; }
public int DepartmentId { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public virtual Department Department { get; set; }
}
}
Department.cs
using System;
using System.Collections.Generic;
namespace EF_DB_First.Models
{
public partial class Department
{
public Department()
{
Employee = new HashSet<Employee>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Employee> Employee { get; set; }
}
}
CompanyContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace EF_DB_First.Models
{
public partial class CompanyContext : DbContext
{
public CompanyContext()
{
}
public CompanyContext(DbContextOptions<CompanyContext> options)
: base(options)
{
}
public virtual DbSet<Department> Department { get; set; }
public virtual DbSet<Employee> Employee { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string
optionsBuilder.UseSqlServer("Server=--;Database=db_name;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<Employee>(entity =>
{
entity.Property(e => e.Designation)
.IsRequired()
.HasMaxLength(25)
.IsUnicode(false);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
entity.HasOne(d => d.Department)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.DepartmentId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Employee_Department");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
Parameters with Scaffold-DbContext
Let’s see the parameter of Scaffold-DbContext there are various parameters with the scaffold DbContext. There are various parameters with the Scaffold-DbContext to customize the model created from the existing database. The parameters in Scaffold-DbContext are as follows,
- Connection<String> – this parameter is used for the connection establishment to the database.
- Provider<String> –this is used to specify which provider name like SqlServer, SQLlite, and so on.
Eg:
Scaffold-DbContext “<connection string>” – provider Microsoft.EntityFrameworkCore.SqlServer
- OutputDir <String> – this parameter is used to specify the directory name to build the model files.
Eg:
Scaffold-DbContext “<connection string>”
- provider Microsoft.EntityFrameworkCore.SqlServer
- OutputDir Models/DB
- ContextDir <String> – this parameter is used to denote the name of the directory to place the Context File
Eg:
Scaffold-DbContext “<connection string>”
- OutputDir Models/DB
-ContextDir Models/Context
- Context <String> –this parameter is used to denote the DbContext name which we used, in the above code we have used the Company database so we specified as CompanyContext by default,
Eg:
Scaffold-DbContext “<connection string>”
- Context CompanyContext
- Schema <String[]> – this parameter is used for accepting the string array which having the Schema Names, we can use desired schema names for the models which we need to be created.
Eg:
Scaffold-DbContext “<connection string>”
- Schemas dbo, admin
- Tables<String[]> – this parameter is used to accept the array string which has the name of the tables for the model classes to be created, sometimes we need not create models for the entire tables in the database. The tables must have the Primary Key for generating Entity Class by using Scaffold-DbContext.
Eg: Scaffold-DbContext “<connection string>”
- Tables Categories, OrderDetails, StoreDetails
- DataAnnotations – this parameter is used for setting Annotations in the Model Classes.
Eg:
Scaffold-DbContext “<connection string>”
- provider Microsoft.EntityFrameworkCore.SqlServer
- DataAnnotations
- Force – this parameter is used for overriding the existing models with new implementations.
Eg:
Scaffold-DbContext “<connection string>”
- provider Microsoft.EntityFrameworkCore.SqlServer
- Force
Conclusion
In this article, I have explained the creation of the Database-First approach in Entity Framework with the Scaffold-DbContext Parameters. The database-First approach is nothing but creating the models and the DbContext classes from an existing database with the help of Scaffold-DbContext Commands. Hope the article helps you to understand.
Recommended Articles
We hope that this EDUCBA information on “Entity Framework Core Database-First” was beneficial to you. You can view EDUCBA’s recommended articles for more information.