У меня есть этот метод расширения:Объединяя два метода расширения в один
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;
}
Я ненавижу идея иметь почти тот же код дважды, как я могу объединить эти два метода в один? (если возможно) или, по крайней мере, сделать это двумя способами, но фильтрация в одном из них? исходный код намного длиннее, что также является одной из причин.
Я собирался прокомментировать, что он не работает, но вы уже обновили ответ :) спасибо в любом случае. –