The post Fast Insert with Entity Framework Core in ASP.NET Core appeared first on Tech Insights.
]]>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 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.
Using fast insert in Entity Framework Core provides several benefits, including:
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.
step-by-step procedure to create an ASP.NET Core project
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.
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": "*" }
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();
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; } } }
Run Migration
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(); } } }
The post Fast Insert with Entity Framework Core in ASP.NET Core appeared first on Tech Insights.
]]>