【发布时间】:2014-02-02 07:19:34
【问题描述】:
我有这个扩展方法:
public static IQueryable<T> FilterByEmployee<T>(this IQueryable<T> source, EmployeeFilter filter)
where T : class, IFilterableByEmployee
{
if (!string.IsNullOrEmpty(filter.Gender))
source = source.Where(e => e.Employee.Gender == filter.Gender);
if (!string.IsNullOrEmpty(filter.NationalityID))
source = source.Where(e => e.Employee.NationalityID == filter.NationalityID);
// filter the group
if (filter.IncludeChildGroups)
{
var groups = Security.GetAllChildGroups(filter.GroupID);
source = source.Where(e => e.Employee.EmployeeGroupID.HasValue
&& groups.Contains(e.Employee.EmployeeGroupID.Value));
}
else
{
source = source.Where(e => e.Employee.EmployeeGroupID == filter.GroupID);
}
// filter status
if (filter.OnlyActiveEmployees)
source = source.Where(e => e.Employee.Status == "Active");
return source;
}
还有一个,完全一样,只是直接过滤Employees上下文:
public static IQueryable<T> Filter<T>(this IQueryable<T> source, EmployeeFilter filter)
where T : Employee
{
if (!string.IsNullOrEmpty(filter.Gender))
source = source.Where(e => e.Gender == filter.Gender);
if (!string.IsNullOrEmpty(filter.NationalityID))
source = source.Where(e => e.NationalityID == filter.NationalityID);
// filter the group
if (filter.IncludeChildGroups)
{
var groups = Security.GetAllChildGroups(filter.GroupID);
source = source.Where(e => e.EmployeeGroupID.HasValue
&& groups.Contains(e.EmployeeGroupID.Value));
}
else
{
source = source.Where(e => e.EmployeeGroupID == filter.GroupID);
}
// filter status
if (filter.OnlyActiveEmployees)
source = source.Where(e => e.Status == "Active");
return source;
}
我讨厌两次使用几乎相同的代码的想法,如何将这两种方法合二为一? (如果可能的话)或者至少使它成为两种方法,但在其中一种中进行过滤?原始代码要长得多,这也是原因之一。
【问题讨论】:
标签: c# entity-framework linq-to-entities extension-methods