Fast Insert with Entity Framework Core in ASP.NET Core

In this article, we will discuss Fast Insert with Entity Framework Core in ASP.NET Core. Entity Framework Core’s fast insert feature enables you to insert multiple records in the database in a single call, which is much faster than inserting records one by one.

ASP.NET Core is a popular framework for building web applications. It provides a robust set of features and tools to build modern, scalable, and high-performance applications. Entity Framework Core is one of the essential components of ASP.NET Core that allows developers to interact with the database using an object-relational mapping (ORM) approach.

When inserting data into the database using Entity Framework Core, developers often face performance issues, especially when dealing with large datasets. In this article, we will discuss how to use Entity Framework Core’s fast insert feature to improve the performance of data insertion.

Fast Insert in Entity Framework Core

Fast insert is a feature of Entity Framework Core that allows you to insert multiple records in the database in a single call. By default, Entity Framework Core inserts record one by one, which can be very slow and time-consuming when dealing with a large dataset. With a fast insert, you can reduce the number of round trips to the database, which improves the performance of data insertion.

Benefits of Fast Insert in Entity Framework Core

Using fast insert in Entity Framework Core provides several benefits, including:

  • Improved performance: Fast insert reduces the number of round trips to the database, which improves the performance of data insertion.
  • Reduced network traffic: Fast insert sends a single SQL statement to the database, reducing the network traffic between the application and the database server.
  • Reduced memory consumption: Fast insert reduces the memory consumption of the application, as it doesn’t have to keep track of multiple entities when inserting data into the database.

Implementing Fast Insert in Entity Framework Core

To use a fast insert in Entity Framework Core, you need to install a package from NuGet. Once you have installed the package, you can use the BulkInsert() extension method to insert multiple records in the database.

Install Required Software

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here
  • SQL Server database from here

Create an ASP.NET Core project

step-by-step procedure to create an ASP.NET Core project

  • Open Visual Studio and click on “Create a new project” on the start page
  • In the “Create a new project” dialog box, select “ASP.NET Core Web Application” from the list of available project templates
  • In the “Create a new ASP.NET Core web application” dialog box, select the “Web Application” template.
  • Choose a name and location for your project, and then click on the “Create” button.

Install NuGet Packages

To add new features or libraries to our project, we may need to install additional packages that can be found on NuGet, a package manager. NET. By installing NuGet packages, we can easily incorporate external code into our project and enhance its functionality.

  • Microsoft Entity Framework Core Sql Server.
  • Microsoft Entity Framework Core Tools.
  • EFCore.BulkExtensions.

Configuring the appsetting.json

Configuring the appsetting.json file is an important step in setting up an ASP.NET Core application. This file allows us to store configuration values and settings that are required by our application. By editing the appsetting.json file, we can easily modify our application’s behavior without having to modify the source code.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "sqlconnection": "Server=(local)\\MSSQL;Database=EFCoreDB;Trusted_Connection=True;MultipleActiveResultSets=true" 

  },
  "AllowedHosts": "*"
}

Configure Program.cs

The program.cs is a file in an ASP.NET Core project that contains the application’s entry point. It is responsible for configuring the application’s services, logging, and middleware pipeline. By editing the code in Program.cs, we can customize the behavior of our ASP.NET Core application and add new functionality as needed

using Asp.netcore_Tutorials.Models; 
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
  

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddDbContext<EfCoreContext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection"))); 

builder.Services.AddControllersWithViews(); 

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Create a Model

A model is a representation of the data that our application will use and manipulate. By creating a model, we define the structure of the data and its relationships with other models. This allows us to easily work with data in our application and perform CRUD (Create, Read, Update, Delete) operations on it.

using System.ComponentModel.DataAnnotations;

namespace Asp.netcore_Tutorials.Models
{
    public class Customers
    {
        [Key]
        public int id { get; set; }
        public string fullName { get; set; }
        public string customertype { get; set; }
        public Guid GetGuid { get; set; }
    }
}

Migration

Run Migration

  • Add-Migration ‘Initial Create’
  • Update-Database

Create a Controller

A controller is responsible for handling HTTP requests, performing business logic, and returning HTTP responses. By creating a controller, we define the endpoints of our application and how they respond to client requests. This enables us to build a functional and responsive web application with the desired behavior.

using Asp.netcore_Tutorials.Models;
using EFCore.BulkExtensions;
using Microsoft.AspNetCore.Mvc;

namespace Asp.netcore_Tutorials.Controllers
{
    public class DataInsertefFastController : Controller
    {
        private readonly EfCoreContext _custdbcontext;
        private TimeSpan TimeSpan;

        public DataInsertefFastController(EfCoreContext custDbcontext)
        {
            _custdbcontext = custDbcontext;
        }
        public async Task<IActionResult> Index()
        {

            List<Customers> Cust_List = new();
            DateTime counterstart = DateTime.Now;

            for ( int k=0; k< 150000; k++)
            {
                Cust_List.Add(new Customers()
                {
                       fullName =  "Custmer_" + k,
                       customertype = "Customer_Type_" + k ,
                       GetGuid  = Guid.NewGuid()
                });
            }
            await _custdbcontext.BulkInsertAsync(Cust_List);         
            TimeSpan = DateTime.Now - counterstart;

            return View();
        }
    }
}
Document

More Related Posts

Fast Insert Entity Framework Core
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments