Skip to content

Instantly share code, notes, and snippets.

@hikalkan
Last active April 17, 2023 20:13
Show Gist options
  • Save hikalkan/74f624c0b42c78fb1619e92b3d1972f8 to your computer and use it in GitHub Desktop.
Save hikalkan/74f624c0b42c78fb1619e92b3d1972f8 to your computer and use it in GitHub Desktop.
//Demo usage
public class HomeController : MyControllerBase
{
private readonly IRepository<MyEntity> _myEntityRepository;
public HomeController(IRepository<MyEntity> myEntityRepository)
{
_myEntityRepository = myEntityRepository;
}
public ActionResult Index()
{
var entities = new List<MyEntity>
{
new MyEntity(),
new MyEntity(),
new MyEntity()
};
_myEntityRepository.Insert(entities); //using the new extension method
return View();
}
}
using System;
using System.Collections.Generic;
using System.Reflection;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
namespace MyProject
{
//Add this class to .Core project
public static class MyRepositoryExtensions
{
public static void Insert<TEntity, TPrimaryKey>(this IRepository<TEntity, TPrimaryKey> repository,
IEnumerable<TEntity> entities)
where TEntity : class, IEntity<TPrimaryKey>, new()
{
var type = Type.GetType("MyProject.MyRepositoryHelper, MyProject.EntityFramework");
var bulkInsertMethod = type.GetMethod("BulkInsert", BindingFlags.Static | BindingFlags.Public);
var genericMethod = bulkInsertMethod.MakeGenericMethod(typeof(TEntity), typeof(TPrimaryKey));
genericMethod.Invoke(null, new object[] { repository, entities });
}
}
}
using System.Collections.Generic;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.EntityFramework.Repositories;
namespace MyProject
{
//Add this class to .EntityFramework project
public static class MyRepositoryHelper
{
public static void BulkInsert<TEntity, TPrimaryKey>(IRepository<TEntity, TPrimaryKey> repository, IEnumerable<TEntity> entities)
where TEntity : class, IEntity<TPrimaryKey>, new()
{
var dbContext = repository.GetDbContext();
dbContext.Set<TEntity>().AddRange(entities);
}
}
}
@hikalkan
Copy link
Author

hikalkan commented Oct 4, 2016

Demonstrates how to extend standard IRepository interface. Adds a Insert overload that gets a list of entities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment