Пишем проект под .net core mvc/ef core. Возникли трудности с пониманием как сделать в контроллере в методе [GET] разбиения на условия для EF CORE, а именно: Если в Get запросе нет параметров, то из таблицы выводит все посты, если есть параметры , то должна срабатывать фильтрация и дополнительные условия WHERE. Как заранее составить linq запрос к базе, где where с заглушками(по умолчанию все), а если параметры с запроса приходят, то запихнуть их значение туда?
1 ответ
Допустим есть модель и объект фильтра для нее :
public class Test
{
public Test(string Title, int Value)
{
this.Title = Title;
this.Value = Value;
}
public string Title { get; set; }
public int Value { get; set; }
public override string ToString()
{
return $"{Title},{Value.ToString()}";
}
}
public class FilterTest
{
public int? ValueEqulas { get; set; }
public string TitleContains { get; set; }
}
Теперь в сервисе реализую фильтр (я сделал как расширение для теста, но в реальном проекте просто как метод в сервисе на слое BLL
). Ниже приведены 2 метода, выполняющие одно и то же двумя способами. Первый более применим к БД (например если вы захоитте в фильтре передавать поле сортировки:
public static class Extension
{
public static IList<Test> ReadByFilterByExpression(this List<Test> test, FilterTest filter = null)
{
Expression<Func<Test, bool>> expressionWhereTest = (t => true);//по умолчанию все
ParameterExpression parameter = Expression.Parameter(typeof(Test), "t");
Expression conditions = null;
if (filter != null)
{
if (filter.ValueEqulas != null)
{
Expression left = Expression.PropertyOrField(parameter, nameof(Test.Value));
Expression right = Expression.Constant(filter.ValueEqulas, typeof(int));
var condition = Expression.Equal(left, right);
if (conditions == null)
conditions = condition;
else
conditions = Expression.AndAlso(conditions, condition);
}
if (!string.IsNullOrEmpty(filter.TitleContains))
{
var condition = Expression.Call(Expression.Property(parameter, nameof(Test.Title)), typeof(string).GetMethods().Where(m => m.Name == "Contains").FirstOrDefault(), Expression.Constant(filter.TitleContains));
if (conditions == null)
conditions = condition;
else
conditions = Expression.AndAlso(conditions, condition);
}
}
if (conditions != null)
expressionWhereTest = Expression.Lambda<Func<Test, bool>>(conditions, parameter);
return test.Where(expressionWhereTest.Compile()).ToList();
}
public static IList<Test> ReadByFilterByLambda(this List<Test> test, FilterTest filter = null)
{
if (filter == null) return test;
return test
.Where(t => !string.IsNullOrEmpty(filter.TitleContains) ? t.Title.Contains(filter.TitleContains): true)
.Where(t => filter.ValueEqulas != null ? t.Value == filter.ValueEqulas : true)
.ToList();
}
Теперь тест:
List<Test> list = new List<Test>() {
new Test("1a",1),
new Test("1b",2),
new Test("1c",3)
};
list.ForEach(l => Console.WriteLine(l));
var l2 = list.ReadByFilterByLambda(new FilterTest() { ValueEqulas = 3 }).ToList();
l2.ForEach(l => Console.WriteLine(l));
Как видно, выбралась одна запись.
Если фильтр пустой:
var l2 = list.ReadByFilterByLambda().ToList();
Как видно выбралось все.
Так же в интернете натыкался и на другой способ реализации фильтров