Entity Framework Core Reverse Engineering

Entity Framework Core Reverse Engineering – Entity Framework Core with Existing Database

Reverse engineering is the process of creating entity classes and DB context using an existing database. This blog is going to explain how to create the Entity Framework Core with an existing database.Let see this by step by step.

Step 1: Create Database and Tables

In this example, I used the local DB to create the Entity Framework Core.

To create a local DB, in the menu click Tools – > Connect to Database… ->  Server Name Provide (localdb)\mssqllocaldb and in select or enter a database name master

Now you can see the master database in Server Explorer. Right-click on the database and choose New Query. Copy and paste the following scripts to create a database and tables in the query window.

Create Database SampleDB
GO
USE SampleDB
GO
CREATE TABLE [dbo].[Department](
    [DepartmentID] [int] IDENTITY(1,1) PRIMARY KEY,
    [DepartmentName] [varchar](100) NULL
    )
GO

CREATE TABLE [dbo].[Student](
    [StudentID] [int] IDENTITY(1,1) PRIMARY KEY,
    [DepartmentID] [int] FOREIGN KEY REFERENCES Department(DepartmentID),
    [StudentName] [varchar](100) NULL,
    )

Step 2: Install Packages

Before creating reverse engineering. You need to install the necessary packages. I have installed packages using the Package Manager Console.

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Install-Package Microsoft.EntityFrameworkCore.Tools

Following is a screenshot of Solution Explorer after installing the required packages.

Solution Explorer

Step 3: Scaffold-DbContext

Here I have created DB models using Scaffold-DbContext. Added database connection string in Scaffold-DbContext. Then added the database provider, here is the database provider SQLServer so Microsoft.EntityFrameworkCore.SqlServer is included. Finally -OutputDir, which puts the models in the Models directory. Run this command in Package Manager Console 

Scaffold-DbContext “Server=(localdb)\mssqllocaldb;Database=SampleDB;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServe -OutputDir Models

See the following screenshot and see how database models are created.

Solution Explorer

The following is the SampleDBContext.cs content. It is created by Scaffold-DbContext.

SampleDBContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace SampleWebApplication.Models
{
    public partial class SampleDBContext : DbContext
    {
        public SampleDBContext()
        {
        }

        public SampleDBContext(DbContextOptions<SampleDBContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Department> Department { get; set; }
        public virtual DbSet<Student> Student { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SampleDB;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Department>(entity =>
            {
                entity.Property(e => e.DepartmentId).HasColumnName("DepartmentID");

                entity.Property(e => e.DepartmentName)
                    .HasMaxLength(100)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Student>(entity =>
            {
                entity.Property(e => e.StudentId).HasColumnName("StudentID");

                entity.Property(e => e.DepartmentId).HasColumnName("DepartmentID");

                entity.Property(e => e.StudentName)
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.HasOne(d => d.Department)
                    .WithMany(p => p.Student)
                    .HasForeignKey(d => d.DepartmentId)
                    .HasConstraintName("FK__Student__Departm__25869641");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

Step 4: Update Entity Framework

Database updating is inevitable, so you need to update the Entity Framework Core as well.Let’s see how to do it. Here I have added a new column called Grade to the student table.

ALTER TABLE Student ADD Grade VARCHAR(100)

The following is a Scaffold-DbContext command to update the Entity Framework Core. I have added -force here to update the Entity Framework Core.

Scaffold-DbContext “Server=(localdb)\mssqllocaldb;Database=SampleDB;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force

The following is a Student.cs file. Here you can see the  public string Grade { get; set; } property is added.

Student.cs
using System;
using System.Collections.Generic;

namespace SampleWebApplication.Models
{
    public partial class Student
    {
        public int StudentId { get; set; }
        public int? DepartmentId { get; set; }
        public string StudentName { get; set; }
        public string Grade { get; set; }

        public virtual Department Department { get; set; }
    }
}

This article explains how to create Entity Framework Core and how to update it.

If you have any questions, please leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *