LINQ: dynamic where with a common property and value

I am trying to create a simple select method to query a Linq-to-SQL table through a common static method. I am fixated on creating an expression dynamically.

There is the same question here: LINQ: dynamic selection

  • T is the database table class (Person)
  • P is the type of value. The types of values ​​and properties must be the same (F.exString)
  • column is the name of the property for this class ("Name")
  • Value is the value of the instruction for the field ("Jack")

F.ex Select all faces where the name is "Jack" = Person.Name = "Jack"

public static List<T> selectBy<T,P>(String column, P value) where T : class { try { // First resolve the used table according to given type Table<T> table = database.GetTable<T>(); // Get the property according to given column PropertyInfo property = typeof(T).GetTypeInfo().GetDeclaredProperty(column); //Func<Data,Data> expressionHere // Select all items that match the given expression List<T> objectList = table.Where(expressionHere).ToList<T>(); // Return the filled list of found objects return objectList; } catch (Exception ex) { Debug.WriteLine("selectBy", ex.Message.ToString()); return null; } } 
0
source share
1 answer

You can build the expression manually as follows:

 // First resolve the used table according to given type Table<T> table = database.GetTable<T>(); // Get the property according to given column PropertyInfo property = typeof(T).GetTypeInfo().GetDeclaredProperty(column); //Func<Data,Data> expressionHere ParameterExpression lambdaArg = Expression.Parameter(typeof(T)); Expression propertyAccess = Expression.MakeMemberAccess(lambdaArg, property); Expression propertyEquals = Expression.Equal(propertyAccess, Expression.Constant(value, typeof(P))); Expression<Func<T, bool>> expressionHere = Expression.Lambda<Func<T, bool>>(propertyEquals, lambdaArg); // Select all items that match the given expression List<T> objectList = table.Where(expressionHere).ToList<T>(); // Return the filled list of found objects return objectList; 
+1
source

Source: https://habr.com/ru/post/987488/


All Articles