Entity Framework Core Database-First Tutorial for .NET Core (2023)

In This Topic

    Entity Framework Core Database-First Tutorial for .NET Core

    In This Topic

    Entity Framework Core supports Database-First approach via the Scaffold-DbContext command of Package Manager Console. This command scaffolds a DbContext and entity type classes for a specified database.

    This tutorial shows how to create a simple console application, powered by Entity Framework Core and using Database-First approach. In less than 10 minutes you will have aready-to-use data access layer for your business objects.

    This tutorial is for .NET Core. For Full .NET Framework see Entity Framework Core Database-First Tutorial for Full .NET Framework.

    Requirements

    This tutorial requires the following:

    • Visual Studio 2017 or higher (for Entity Framework Core 3.1 - Visual Studio 2019)
    • If you want to use Entity Framework Core 2.2 - .NET Core SDK 2.2. For Entity Framework Core 3.1 - .NET Core SDK 3.0
    • Latest version of NuGet Package Manager
    • Latest version of Windows PowerShell

    We will use the tables, we have created in the Creating Database Objects and Inserting Data Into Tables tutorials. In this tutorial it is assumed that you already have the database objects created. If you haven't created them yet, please do it before starting this tutorial.

    Creating New Project

    1. Open Visual Studio
    2. On the File menu point to New and then click Project. The New Project dialog box will open.
    3. On the left side of the dialog box select Installed -> Visual C# -> .NET Core.
    4. On the right side of the dialog box select Console App.
    5. Enter the project name and location if necessary.
    6. Click OK. A new project will be created.

    Installing NuGet Packages

    After we created a new project, we need to add the necessary NuGet packages to it.

    (Video) Entity Framework Core Database First CRUD in MVC ASP.NET Core

    Now let's install the necessary packages:

    1. On the Tools menu point to NuGet Package Manager and then click Package Manager Console.
    2. For Entity Framework Core 5, run the following command in the Package Manager Console:
      Install-Package Microsoft.EntityFrameworkCore.Tools
    3. For Entity Framework Core 3.1, run the following command in the Package Manager Console:
      Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.10

      For Entity Framework Core 2.2, run the following command in the Package Manager Console:

      Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.2.6

      For Entity Framework Core 1.1, the command will be the following:

      Install-Package Microsoft.EntityFrameworkCore.Tools -Version 1.1.5
    4. For Entity Framework Core 3.1 or 5.0 run the following command in the Package Manager Console:
      Install-Package Devart.Data.PostgreSql.EFCore

      For Entity Framework Core 1.1, the command will be the following:

      Install-Package Devart.Data.PostgreSql.EFCore.Design

    Note that the dotConnect for PostgreSQL assembly for Entity Framework Core 2.2 is not available via NuGet packages anymore. It is installed by the dotConnect for PostgreSQL installer to the \Entity\EFCore2\netstandard2.0\ subfolder of the dotConnect for PostgreSQL installation folder.

    Creating a Model From the Database

    For Entity Framework Core, creating a model from the database is as easy as entering the Scaffold-DbContext command with a connection string and a provider as parameters. For example, you can run the following command in the Package Manager Console:

    Scaffold-DbContext "host=server;database=test;user id=postgres;" Devart.Data.PostgreSql.Entity.EFCore

    If you have other tables in your database, you may use additional parameters - -Schemas and -Tables - to filter the list of schemas and/or tables that are added to the model. For example, you can use the following command:

    Scaffold-DbContext "host=server;database=test;user id=postgres;" Devart.Data.PostgreSql.Entity.EFCore -Tables dept,emp

    As the result, a context class and entity classes are generated, based on the Dept and Emp tables.

    (Video) ASP.NET Core Web API + Entity Framework Core : Database First - EP01

    • C#
    using System;using System.Collections.Generic;namespace ConsoleApplication1{ public partial class Dept { public Dept() { Emp = new HashSet<Emp>(); } public int Deptno { get; set; } public string Dname { get; set; } public string Loc { get; set; } public virtual ICollection<Emp> Emp { get; set; } }}
    • C#
    using System;using System.Collections.Generic;namespace ConsoleApplication1{ public partial class Emp { public int Empno { get; set; } public string Ename { get; set; } public string Job { get; set; } public int Mgr { get; set; } public DateTime Hiredate { get; set; } public double Sal { get; set; } public double Comm { get; set; } public int Deptno { get; set; } public virtual Dept DeptnoNavigation { get; set; } }}

    Entity classes are just simple classes, representing the data, stored in the database. The context represents a session with the database and allows you to query and save instances of the entity classes.

    • C#
    using System;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Metadata;namespace ConsoleApplication1{ public partial class ModelContext : DbContext { public virtual DbSet Dept { get; set; } public virtual DbSet Emp { 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. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UsePostgreSql(@"host=server;database=test;user id=postgres;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Dept>(entity => { entity.HasKey(e => e.Deptno) .HasName(""); entity.ToTable("DEPT", "public"); entity.Property(e => e.Deptno).HasColumnName("DEPTNO"); entity.Property(e => e.Dname) .HasColumnName("DNAME") .HasColumnType("varchar") .HasMaxLength(14); entity.Property(e => e.Loc) .HasColumnName("LOC") .HasColumnType("varchar") .HasMaxLength(13); }); modelBuilder.Entity<Emp>(entity => { entity.HasKey(e => e.Empno) .HasName(""); entity.ToTable("EMP", "public"); entity.Property(e => e.Empno).HasColumnName("EMPNO"); entity.Property(e => e.Comm) .HasColumnName("COMM") .HasColumnType("double"); entity.Property(e => e.Deptno).HasColumnName("DEPTNO"); entity.Property(e => e.Ename) .HasColumnName("ENAME") .HasColumnType("varchar") .HasMaxLength(10); entity.Property(e => e.Hiredate) .HasColumnName("HIREDATE") .HasColumnType("date"); entity.Property(e => e.Job) .HasColumnName("JOB") .HasColumnType("varchar") .HasMaxLength(9); entity.Property(e => e.Mgr).HasColumnName("MGR"); entity.Property(e => e.Sal) .HasColumnName("SAL"); entity.HasOne(d => d.DeptnoNavigation) .WithMany(p => p.Emp) .HasForeignKey(d => d.Deptno) .HasConstraintName("emp_deptno_fkey"); }); } }}

    Here we may comment or delete the warning about the connection string. After this we can start using our model to retrieve and modify data.

    (Video) Getting Started with Entity Framework Core [1 of 5] | Entity Framework Core for Beginners

    Using Model

    Open your Program.cs file and paste the following code instead of the Main function:

    • C#
     static void Main(string[] args) { using (var db = new ModelContext()) { // Creating a new department and saving it to the database var newDept = new Dept(); newDept.Deptno = 60; newDept.Dname = "Development"; newDept.Loc = "Houston"; db.Dept.Add(newDept); var count=db.SaveChanges(); Console.WriteLine("{0} records saved to database", count); // Retrieving and displaying data Console.WriteLine(); Console.WriteLine("All departments in the database:"); foreach (var dept in db.Dept) { Console.WriteLine("{0} | {1}", dept.Dname, dept.Loc); } } }

    After this, on the Debug menu, click Run without debugging.

    Entity Framework Core Database-First Tutorial for .NET Core (1)

    See Also

    Compatibility

    © 2003 - 2023 Devart. All Rights Reserved.

    [emailprotected]

    (Video) Entity Framework core 7.0 ( DB First Approach & Code First Approach) | .NET 7 Updates

    (Video) EF Core 6 🚀 Database First / DB First (Entity Framework Core 6 / .NET 6)

    FAQs

    How to use database first approach in Entity Framework Core? ›

    This article is about Entity Framework with . Net Core MVC, Database-First approach.
    1. Step 1: Create an ASP.NET Core MVC application.
    2. Step 2: Reverse engineer Entity model from database (database first approach for entity)
    3. Step 3: Scaffold Controller with View using Entity Framework.
    4. Step 4: Run and Test app.
    Dec 16, 2022

    What is code first and database First in Entity Framework Core? ›

    In the code first approach, the programmer has to write the classes with the required properties first, while in the database first approach, the programmer has to create first the database using GUI.

    How to use Entity Framework Core in .NET Core? ›

    Introduction
    1. Step 1: Create an ASP.NET MVC application.
    2. Step 2: Add a Model.
    3. Step 3: Set up DbContext.
    4. Step 4: Set up Data Connection.
    5. Step 4.5: Migrate and Update database (this step is not necessary for . Net Framework MVC)
    6. Step 5: Create Controller to access data from entity framework.
    7. Step 6: Run the App and Test.
    Dec 16, 2022

    Which is better code first or database first in Entity Framework? ›

    Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.

    How use raw SQL query in Entity Framework Core? ›

    The FromSql method allows parameterized queries using string interpolation syntax in C#, as shown below. string name = "Bill"; var context = new SchoolContext(); var students = context. Students . FromSql($"Select * from Students where Name = '{name}'") .

    How do you retrieve data from database using Entity Framework first? ›

    Fetch Data Through Entity Framework
    1. Create a new Asp.NET Empty Web Site. Click on File, WebSite, then ASP.NET Empty Web Site.
    2. Install EntityFramework through NuGet.
    3. Table Structure. ...
    4. Now, add the Entity Data Model,
    5. Select Generate from database.
    6. Select connection,
    7. Select table,
    8. After that click on Finish button,
    Nov 5, 2018

    How do I create a DbContext in Entity Framework core database first? ›

    Entity Framework Core Database First Tutorial
    1. Create Northwind Database. ...
    2. Create New . ...
    3. Install Nuget Packages. ...
    4. Create Models using Scaffold-DbContext. ...
    5. Configure Data Context. ...
    6. Registering DBContext with Dependency Injection. ...
    7. Scaffold-DbContext options. ...
    8. Update existing models.
    Dec 3, 2021

    What is the difference between code first and model first Entity Framework? ›

    Code first approach is used to fast development and developer has full controls on entities. Model First approach : We don't have an existing database and the Entity Framework offers a designer that can create a conceptual data model. It also uses an . edmx file to store the model and mapping information.

    How do you create a database from code first in .NET core? ›

    Create A New Database Using Code First In Entity Framework
    1. Step 1 - Create Windows form project. ...
    2. Step 2 - Add entity frame work into newly created project using NuGet package. ...
    3. Step 3 - Create Model into project. ...
    4. Step 4 - Create Context class into project. ...
    5. Step 5 - Exposed typed DbSet for each classes of model.
    Jun 3, 2016

    How to use code first approach in Entity Framework? ›

    Code First Approach in MVC: Everything You Need to Know
    1. Create a blank database.
    2. Create MVC Project.
    3. Create the Class Library Project.
    4. Add Entity Framework to the DAL project created in the previous step. ...
    5. Code First Approach Implementation.
    6. Reference DAL Project to UI Project. ...
    7. Enable Migration.
    8. Add Controller.
    Feb 25, 2021

    How do I use model first approach in Entity Framework? ›

    In Model First, you define your model in an Entity Framework designer then generate SQL, which will create database schema to match your model and then you execute the SQL to create the schema in your database. The classes that you interact with in your application are automatically generated from the EDMX file.

    Which approach does EF core support to work with the database? ›

    EF supports the following model development approaches: Generate a model from an existing database. Hand code a model to match the database. Once a model is created, use EF Migrations to create a database from the model.

    How to retrieve data from database using Entity Framework Core? ›

    To retrieve data from an existing database in EF Core, you should do the following step:
    1. Create an App. Create an ASP.NET Core app . ...
    2. Create the Models. Create a model for your existing SQL Server database. ...
    3. Create a Context. ...
    4. Configure database connection. ...
    5. Add AddDbContext service. ...
    6. Add-Migration and Update-Database command.
    Jun 11, 2022

    Videos

    1. ENTITY FRAMEWORK CORE 6 IN URDU HINDI | MIGRATION IN ENTITY FRAMEWORK CORE | CODE FIRST DB FIRST
    (Recital Learning)
    2. How to use Entity Framework Core in ASP.NET Core 6.0 MVC | Database First Approach
    (Nihira Techiees)
    3. CRUD Operations Using Database First Approach In Entity Framework Core 6 and ASP.NET Core MVC 6
    (tutorpraveen)
    4. ASP.NET Core - Scaffolding with Entity Framework Core (Database first approach)
    (Computerix)
    5. ASP.NET Core 6 Web API Using Entity Framework Core 6 Database First Approach | REST API
    (tutorpraveen)
    6. Entity Framework Core Database First Approach - Build ASP.NET Core Razor Pages App using EF Core
    (Sameer Saini)
    Top Articles
    Latest Posts
    Article information

    Author: Terrell Hackett

    Last Updated: 11/10/2022

    Views: 6238

    Rating: 4.1 / 5 (52 voted)

    Reviews: 91% of readers found this page helpful

    Author information

    Name: Terrell Hackett

    Birthday: 1992-03-17

    Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

    Phone: +21811810803470

    Job: Chief Representative

    Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

    Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.