是的,使用泛型和
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
}