EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials Database Management Tutorial Entity Framework Core Database-First
Secondary Sidebar
Dot NET
  • .Net
    • What is .Net?
    • What is .NET Core
    • .NET Framework Architecture
    • Career in ASP.NET
    • ASP.NET Core JWT Authentication
    • Uses of .Net
    • .NET Interview Questions
    • How to Install .NET
    • MVC Architecture
    • Entity Framework Migration
    • Entity Framework Core Database-First
    • Entity Framework Find
    • Entity Framework Extensions
    • Entity Framework Join LINQ
    • Entity Framework SaveChanges
    • Entity Framework Navigation Properties
    • Entity Framework Relationships
    • Entity Framework One to Many
    • Entity Framework Left Join
    • Entity Framework Group By
    • Entity Framework Stored Procedure
    • Entity Framework with MongoDB
    • Entity Framework LINQ
    • Entity Framework Repository Pattern
    • Entity Framework in MVC
    • Entity Framework in .Net Core
    • Entity Framework NuGet
    • ViewModel in MVC
    • MVC DropDownList
    • MVC ViewData
    • Partial View in MVC
    • TempData in MVC
    • Aggregation in OOPS
    • LINQ OrderBy Desc
    • LINQ orderby
  • VB.NET
    • What is VB.Net
    • VB.Net Data Types
    • VB.NET Operators
    • VB.Net Loops
    • VB.Net for Loop
    • VB.NET Controls
    • Inheritance in VB.Net
    • Exception Handling in VB.NET
    • VB.Net Events
    • VB.Net String Functions
    • VB.NET Interview Questions
  • ADO.NET
    • What is ADO.NET
    • ADO.NET Interview Questions
  • LINQ
    • LINQ Include
    • LINQ Aggregate
    • LINQ Distinct
    • LINQ Inner Join
    • LINQ Left Join
    • LINQ Except
    • LINQ SelectMany
    • LINQ Union
    • LINQ Sum
    • LINQ any
    • LINQ Where
    • LINQ Contains
    • LINQ Intersect
    • LINQ Join
    • LINQ Select
    • LINQ Sort

Related Courses

.NET Course Training

VB.NET Training Course

ADO.NET Training Course

Entity Framework Core Database-First

Entity Framework Core Database-First

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.

Framework Core Database 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.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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,

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,408 ratings)

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

This is a guide to Entity Framework Core Database-First. Here we discuss the introduction, overviews, How to create a database entity framework core Database, and parameters with scaffold-DbContext. You may also have a look at the following articles to learn more –

  1. ASP.NET Core Entity Framework
  2. ADO.Net vs Entity framework
  3. Entity Framework Interview Questions
  4. Entity Framework Insert
Popular Course in this category
SQL Training Program (7 Courses, 8+ Projects)
  7 Online Courses |  8 Hands-on Projects |  73+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

PL SQL Training (4 Courses, 2+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more