in my solution there are two projects: a .net core class library named "Infrastructure" and a .net core web application (mvc) named "Admin". In the "Infrastructure" prj I've implemented the Repository Pattern for Application DBContext like:
public partial class ApplicationDbContext : DbContext
{
....
}
Interfaces:
public interface IGenericRepository<T> where T : class
{
T Add(T t);
....
}
public interface ICustomersRepository : IGenericRepository<Customers>
{
Customers GetCustomerByCompanyCode(string companyCode);
void InsertOrUpdate(Customers toSync);
}
Generic:
public class GenericRepository<T> : IGenericRepository<T>, where T : class
{
protected ApplicationDbContext _context;
public GenericRepository(ApplicationDbContext context)
{
_context = context;
}
public virtual T Add(T t)
{
_context.Set<T>().Add(t);
_context.SaveChanges();
return t;
}
....
}
Specific:
public class CustomersRepository : GenericRepository<Customers>, ICustomersRepository
{
public CustomersRepository(ApplicationDbContext context) : base(context)
{
}
....
}
In the Web Application: - Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
....
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped<ICustomersRepository, CustomersRepository>();
....
}
- CustomersController.cs
private readonly ICustomersRepository rep;
public CustomersController(ICustomersRepository rep, ....)
{
this.rep = rep;
....
}
public async Task DoImport()
{
....
rep.InsertOrUpdate(mapper.Map<Customers>(item.Result));
....
}
It works but very slowly: 300.000 insert in few hours. If I don't use Repository Pattern but try to insert calling ApplicationDBContext directly like:
using (var _context = new ApplicationDbContext())
{
_context.Add(toSync);
_context.SaveChanges();
}
the work time is: 300.000 insert in 6 minutes.
Why is this happening? Is the Repository Pattern the best choice to separate Data Access Layer in .net core projects? There are other solutions to do this? Tnx in advance.