Loading, please wait...

A to Z Full Forms and Acronyms

Setup Entity Framework Core with Blazor Application | Blazor Tutorials.

In this article, we will discuss adding database support for ASP.NET Core REST API service. For this, we are going to use Entity Framework Core.

Before getting into this article, we would suggest you please read all our other Blazor articles for more and sequential information about ASP .NET Core Blazor with the links below:

  1. Chapter 1: Blazor Interview Questions and Answers
  2. Chapter 2: What is ASP.NET Core Blazor?
  3. Chapter 3: Blazor Vs Angular
  4. Chapter 4: Blazor hosting models
  5. Chapter 5: Project Structure in Blazor
  6. Chapter 6: What are Blazor Components
  7. Chapter 7: net core razor components in details | Nesting Razor Components
  8. Chapter 8: Blazor Model Classes
  9. Chapter 9: Data Bindings in Blazor
  10. Chapter 10: Data access technique in blazor

Entity Framework Core

Entity Framework Core is an ORM (i.e an Object-Relational Mapper). It's a finished revise from the beginning. On the off chance that you have any involvement in past adaptations of Entity Framework, you will discover a ton of natural highlights.

EF core is lightweight, extensible, and open-source programming. Like .NET Core, EF Core is additionally cross-stage. It deals with Windows, Mac OS, and Linux. EF Core is Microsoft's legitimate information to get to the stage.

Entity Framework Core DbContext class

One of the significant classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to communicate with the basic database. It is this class that deals with the database association and is utilized to recover and spare information in the database.

To utilize the DbContext class in our application

We make a class that gets from the DbContext class.

DbContext class is on Microsoft.EntityFrameworkCore namespace.

public class AppDbContext : DbContext
{ }

DbContextOptions in Entity Framework Core

For the DbContext class to have the option to accomplish any valuable work, it needs an occurrence of the DbContextOptions class.

The DbContextOptions case conveys design data, for example, the association string, database supplier to utilize, and so on.

We pass the DbContextOptions to the base DbContext class constructor utilizing the base watchword as demonstrated as follows.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
}

Entity Framework Core DbSet

The DbContext class incorporates a DbSet<TEntity> property for every entity in the model.

Right now in our application, we have 2 entity classes - Employee and Department.

So in our AppDbContext class, we have 2 relating DbSet properties.

DbSet<Employee>
DbSet<Department>

We will utilize these DbSet properties to question and spare occurrences of Employee and Department classes.

The LINQ questions against the DbSet properties will be converted into inquiries against the fundamental database.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Employees { get; set; }
}

Seeding Data

Abrogate the OnModelCreating strategy to seed Employee and Department data.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    
    // Code to seed data
}

AppDbContext class total code

Make a Models envelope and incorporate the accompanying AppDbContext class in it.

using EmployeeManagement.Models;
using Microsoft.EntityFrameworkCore;
using System;

namespace EmployeeManagement.Api.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
        {
        }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Department> Departments { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //Seed Departments Table
            modelBuilder.Entity<Department>().HasData(
                new Department { DepartmentId = 1, DepartmentName = "IT" });
            modelBuilder.Entity<Department>().HasData(
                new Department { DepartmentId = 2, DepartmentName = "HR" });
            modelBuilder.Entity<Department>().HasData(
                new Department { DepartmentId = 3, DepartmentName = "Payroll" });
            modelBuilder.Entity<Department>().HasData(
                new Department { DepartmentId = 4, DepartmentName = "Admin" });

            // Seed Employee Table
            modelBuilder.Entity<Employee>().HasData(new Employee
            {
                EmployeeId = 1,
                FirstName = "John",
                LastName = "Hastings",
                Email = "David@pragimtech.com",
                DateOfBrith = new DateTime(1980, 10, 5),
                Gender = Gender.Male,
                DepartmentId = 1,
                PhotoPath = "images/john.png"
            });

            modelBuilder.Entity<Employee>().HasData(new Employee
            {
                EmployeeId = 2,
                FirstName = "Sam",
                LastName = "Galloway",
                Email = "Sam@pragimtech.com",
                DateOfBrith = new DateTime(1981, 12, 22),
                Gender = Gender.Male,
                DepartmentId = 2,
                PhotoPath = "images/sam.jpg"
            });

            modelBuilder.Entity<Employee>().HasData(new Employee
            {
                EmployeeId = 3,
                FirstName = "Mary",
                LastName = "Smith",
                Email = "mary@pragimtech.com",
                DateOfBrith = new DateTime(1979, 11, 11),
                Gender = Gender.Female,
                DepartmentId = 1,
                PhotoPath = "images/mary.png"
            });

            modelBuilder.Entity<Employee>().HasData(new Employee
            {
                EmployeeId = 4,
                FirstName = "Sara",
                LastName = "Longway",
                Email = "sara@pragimtech.com",
                DateOfBrith = new DateTime(1982, 9, 23),
                Gender = Gender.Female,
                DepartmentId = 3,
                PhotoPath = "images/sara.png"
            });
        }
    }
}

Install required NuGet packages

Install the following 2 NuGet packages.

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Database Connection String

Include the following database connection string in appsettings.json file of the REST API project.

"ConnectionStrings": {
  "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true"
}

ConfigureServices in API project Startup class

Read the connection string from appsettings.json file

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));

    services.AddControllers();
}

Create and execute database migrations

Use the following 2 commands to create and execute the initial database migration

     Add-Migration InitialCreate

     Update-Database

A to Z Full Forms and Acronyms