Skip to content

Instantly share code, notes, and snippets.

@rdbhandari
Created August 18, 2024 03:10
Show Gist options
  • Select an option

  • Save rdbhandari/7cfefe20d6675e9a07a87540238e7106 to your computer and use it in GitHub Desktop.

Select an option

Save rdbhandari/7cfefe20d6675e9a07a87540238e7106 to your computer and use it in GitHub Desktop.
Custom Seeder MiddleWare Using CSV Hellper

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>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment