add below line to Program.cs
app.UseCustomSeeder<EntityType , DBContext>("path\path\file.csv");
| using AutoMapper; | |
| using CsvHelper; | |
| using CsvHelper.Configuration; | |
| using Microsoft.AspNetCore.Builder; | |
| using Microsoft.AspNetCore.Http; | |
| using Microsoft.EntityFrameworkCore; | |
| using Microsoft.Extensions.Configuration; | |
| using System.Globalization; | |
| using System.Threading.Tasks; | |
| namespace SBMS_Backend.Seeder | |
| { | |
| // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project | |
| public class CustomSeeder | |
| { | |
| private readonly RequestDelegate _next; | |
| public CustomSeeder(RequestDelegate next) | |
| { | |
| _next = next; | |
| } | |
| public Task Invoke(HttpContext httpContext) | |
| { | |
| return _next(httpContext); | |
| } | |
| } | |
| // Extension method used to add the middleware to the HTTP request pipeline. | |
| public static class CustomSeederExtensions | |
| { | |
| public static IApplicationBuilder UseCustomSeeder<T, TContext> (this IApplicationBuilder builder, string path, CsvConfiguration? config = null) where T : class where TContext : DbContext | |
| { | |
| if (config == null) { | |
| config = new CsvConfiguration(CultureInfo.InvariantCulture) | |
| { | |
| HasHeaderRecord = true, | |
| Quote = '"', | |
| Escape = '\'', | |
| Encoding = System.Text.Encoding.UTF8, | |
| BadDataFound = null | |
| }; | |
| } | |
| using (var servicescope = builder.ApplicationServices.CreateScope()) | |
| { | |
| var context = servicescope.ServiceProvider.GetService<TContext>(); | |
| if (context != null) | |
| { | |
| try | |
| { | |
| if (!context.Set<T>().Any()) | |
| { | |
| using (var reader = new StreamReader(path)) | |
| using (var csvReader = new CsvReader(reader, config)) | |
| { | |
| IEnumerable<T> records = csvReader.GetRecords<T>(); | |
| foreach (T record in records) | |
| { | |
| context.Set<T>().Add(record); | |
| } | |
| } | |
| context.SaveChanges(); | |
| Console.WriteLine("Succesfully Seeded Data For : " + typeof(T)); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| Console.WriteLine("Ex -> : " + ex.ToString()); | |
| return builder.UseMiddleware<CustomSeeder>(); | |
| } | |
| } | |
| } | |
| return builder.UseMiddleware<CustomSeeder>(); | |
| } | |
| } | |
| } |