Entity Framework Core – Database First

Database priority is that EF Core will automatically create Entity & amp;Context according to the database, so you have to create the database first

Let’s make a demonstration through a Company database

1 Create a database in SQL Server

Open View->SQL Sever Object Explorer in Visual Studio, then create a simple database named Company, and create two tables in the database:

  • Employee

  • department

The Employee table is defined as follows:

The Department table is defined as follows:

The Primary Key of these two tables is the Id column and self-growth

Department & Employee is a one-to-many relationship. A Department has multiple Employees. We create the DepartmentId column in the Employee table as the foreign key of the Department table.

create table script

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]
go
SET ANSI_PADDING OFF
go
ALTERTABLE [dbo].[Employee] WITHCHECKADDCONSTRAINT [FK_Employee_Department] FOREIGNKEY([DepartmentId])
REFERENCES [dbo].[Department] ([Id])
go
ALTERTABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Department]
go

2 Entity Framework Core database connection string

The database connection string contains the data source and some necessary connection information. EF Core needs the connection string to interact with the database. Specify database operations such as adding, reading, etc. Open SQL Sever Object Explorer, select the database with the mouse, and right-click Properties , find Connection String in the properties pane and copy the value

The database connection string is:

Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

3 .NET Core CLI Scaffold commands

Run the CLI Scaffold command in the Package Manager Console form, and open the Tools->NuGet Package Manager->Package Manager Console menu in Visual Studio

Before running, please make sure that you have installed the EF Core related tool chain in the project, run the command as follows:

dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

explain:

  • The database connection character is specified in double quotes

  • Microsoft.EntityFrameworkCore.SqlServer specifies the Provider that uses SQL Server

  • -o Models specifies the directory name for generating Entity & amp; Context classes

This command needs to be executed for 10-20 seconds. After execution, we can see the generated class

3.1 Context & Entity class

We found that the context & amp; entity class was generated under the Models directory


3.2 Employee class

publicpartialclassEmployee
{
    publicint Id { get; set; }
    publicint DepartmentId { get; set; }
    publicstring Name { get; set; } = null!;
    publicstring Designation { get; set; } = null!;
    public virtual Department Department { get; set; } = null!;
}

3.3 Department class

publicpartialclassDepartment
{
    publicint Id { get; set; }
    publicstring Name { get; set; } = null!;
    publicvirtual ICollection<Employee> Employees { get; } = new List<Employee>();
}

3.4 CompanyContext class

publicpartialclassCompanyContext: DbContext
{
    public CompanyContext()
    {
    }
    public CompanyContext(DbContextOptions<CompanyContext> options)
        : base(options)
    {
    }
    publicvirtual DbSet<Department> Departments { get; set; }
    publicvirtual DbSet<Employee> Employees { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com /fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseSqlServer("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;");
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder. Entity<Department>(entity =>
        {
            entity.ToTable("Department");

            entity.Property(e => e.Name)
                .HasMaxLength(50)
                .IsUnicode(false);
        });
        modelBuilder. Entity<Employee>(entity =>
        {
            entity.ToTable("Employee");

            entity.Property(e => e.Designation)
                .HasMaxLength(25)
                .IsUnicode(false);
            entity.Property(e => e.Name)
                .HasMaxLength(100)
                .IsUnicode(false);

            entity.HasOne(d => d.Department).WithMany(p => p.Employees)
                .HasForeignKey(d => d.DepartmentId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Employee_Department");
        });
        OnModelCreatingPartial(modelBuilder);
    }
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

4 PMC Scaffold-DbContext commands

We can skip the dotnet cli scaffold command and use the Scaffold-DbContext command in the Package Manager Console to create the Context & amp; Entity class from the database, which is exactly the same as above, run the following command in the Package Manager Console

Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Summary

In this section, we mainly learn about Entity Framework Core database first, and use scaffolding commands to generate corresponding Entity & amp; Context according to the database. However, database first is not recommended. Microsoft recommends that we use the code first method in the next section We’ll look at the DbContext class

References

[1]

Database-First approach in Entity Framework Core

original address