Да, используя обобщенные значения и метод Set<T>()
для DbContext
, вы можете сделать что-то вроде этого:
//Note we need to make the entity and the model it maps to generic
public IEnumerable<TModel> GetAll<TEntity, TModel>(
params Expression<Func<TEntity, object>>[] includes)
where TEntity : class
{
var result = _context.Set<TEntity>().AsQueryable();
if(includes != null)
{
foreach (var include in includes)
{
result = result.Include(include);
}
}
return _mapper.Map<IList<TModel>>(result);
}
И назовите это так:
var allTheThings = GetAll<Commodity, CommodityViewModel>(i => i.OmsCommodityMaterial);
Однако возвращать все ваших строк почти наверняка плохая идея, так почему бы не добавить фильтр, пока мы здесь:
public IEnumerable<TModel> Get<TEntity, TModel>(
Expression<Func<TEntity, bool>> predicate,
params Expression<Func<TEntity, object>>[] includes)
where TEntity : class
{
var result = _context.Set<TEntity>()
.Where(predicate);
if(includes != null)
{
foreach (var include in includes)
{
result = result.Include(include);
}
}
return _mapper.Map<IList<TModel>>(result);
}
Теперь мы называем это так:
var someOfTheThings = Get<Commodity, CommodityViewModel>(
x => x.SomeProperty == 42,
i => i.OmsCommodityMaterial);
Если вы хотите извлечь интерфейс из этого метода, я, вероятно, сделаю интерфейс универсальным:
public interface IOMSService<TEntity>
{
IEnumerable<TModel> Get<TModel>(
Expression<Func<TEntity, bool>> predicate,
params Expression<Func<TEntity, object>>[] includes)
}
А затем базовый класс:
public abstract class BaseOMSService<TEntity> : IOMSService<TEntity>
where TEntity : class
{
private MyDBContext _context;
private IMapper _mapper;
public BaseOMSService(MyDBContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public IEnumerable<TModel> Get<TModel>(
Expression<Func<TEntity, bool>> predicate,
params Expression<Func<TEntity, object>>[] includes)
{
var result = _context.Set<TEntity>()
.Where(predicate);
if(includes != null)
{
foreach (var include in includes)
{
result = result.Include(include);
}
}
return _mapper.Map<IList<TModel>>(result);
}
}
И теперь вы можете создавать определенные производные классы:
public class CheeseOMSService : BaseOMSService<Cheese>
{
// snip
}
public class ZombieOMSService : BaseOMSService<Zombie>
{
// snip
}