我有以下扩展方法:
public static IQueryable<Employee> WhereStatus(this IQueryable<Employee> queryable, string status)
{
var result = queryable
.Where(e => e.EmployeeStatus.Where(s => s.StatusEndDate == null).Select(s => s.Status)
.FirstOrDefault() == status);
return result;
}
public static IQueryable<Employee> WhereCostCenter(this IQueryable<Employee> queryable, int costCenterID)
{
var result = queryable
.Where(e => e.CostCenterID == costCenterID);
return result;
}
我几乎在每一个 LINQ 查询中都需要这些扩展方法,以根据几个参数(例如:状态、成本中心、性别......等)过滤对某些员工的查询。现在我像这样使用它:
using (DB db = new DB())
{
var emps = from em in db.Employees
.WhereStatus("Active")
.WhereCostCenter(112)
select em.EmpID;
var courses = from cr in db.Courses
where c.Contains(cr.EmpID)
select cr;
// now I have the filtered list of the courses I want
.....
}
问题:这是最佳实践吗?或者有没有办法让扩展方法适用于我拥有的所有实体类型,因为所有实体都有一个 EmpID?就像是:
var courses = from em in db.Courses
.WhereStatus("Active") // use the extension methods directly here as well
.WhereCostCenter(112)
select cr;