简体   繁体   中英

EF Core - search properties by string

I have a table with a few hundred columns, and from my client I'm passing multiple 'search' objects to the server used to query this table. Each search object contains a search term, and the name of the property to match it against.

I'm not sure how to use reflection here to query the property using EF Core. I have tried the following but it didn't like it.

var prop = <ENTITYTYPE>.GetProperty(search.Property);

query = context.<ENTITY>.Where(x => (string)prop.GetValue(x) == search.SearchTerm);

I'm thinking that I might have to construct a raw SQL query, but I would love to know if there's a way I can jig it so that EF Core creates the query itself. When I do a .ToList() on the above, it says that the query cannot be translated.

Any help would be appreciated!

This is basic realization which should push you in the right direction:

public static IQueryable<T> AddFilter<T>(IQueryable<T> query, string propertyName, string searchTerm)
{
    var param = Expression.Parameter(typeof(T), "e");
    var propExpression = Expression.Property(param, propertyName);
    
    object value = searchTerm;
    if (propExpression.Type != typeof(string))
        value = Convert.ChangeType(value, propExpression.Type);

    var filterLambda = Expression.Lambda<Func<T, bool>>(
        Expression.Equal(
            propExpression,
            Expression.Constant(value)
        ),
        param
    );

    return query.Where(filterLambda);
}

This method should work well for single instance entities.

public IQueryable<T> GetBySearchTerm(IQueryable<T> queryable, string search)
{
    void GenerateLambda<T>(IProperty columnProp, MethodInfo methodInfo, List<Expression<Func<T, bool>>> expressions)
    {
        if (columnProp.ClrType == typeof(string))
        {
            // Define the parameter
            ParameterExpression xParam = Expression.Parameter(typeof(T), "x");
            // Create the expression representing what column to do the search on
            MemberExpression colExpr = Expression.Property(xParam, columnProp.Name);
            // Create a constant representing the search value
            ConstantExpression constExpr = Expression.Constant(search);
            // Generate a method body that represents "column contains search"
            MethodCallExpression lambdaBody = Expression.Call(colExpr, methodInfo, constExpr);
            // Convert the full expression into a useable query predicate
            Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(lambdaBody, xParam);
            expressions.Add(lambda);
        }
    }

    T thisEntityBaseModel = new T();
   
    IEntityType set = _dbContext.Model.GetEntityTypes().First(x => x.ClrType.Name.ToUpper() == thisEntityBaseModel.ModelName.ToUpper());
    List<Expression<Func<T, bool>>> predicateArray = new List<Expression<Func<T, bool>>>();

    MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    
    foreach (IProperty columnProp in set.GetProperties())
    {
        GenerateLambda(typeof(T), columnProp, containsMethod, predicateArray);
    }


    // This performs an "OR" method on the predicates, since by default it wants to do "AND"
    var predicate = PredicateBuilder.False<T>();
    foreach (Expression<Func<T, bool>> expression in predicateArray) {
        predicate = predicate.Or(expression);
    }

    // Process the ors
    return (queryable.Where(predicate));
}

Not recommended to use, see comments I tried sample below and it works for me

private void Test()
{

    Type myType = typeof(AktivEvents);

    PropertyInfo myPropInfo = myType.GetProperty("AutoReplyMessage");

    Func<AktivEvents, bool> func = (e) => (string)myPropInfo.GetValue(e) == "asdasd";


    var query = _dbService.AktivEvents.GetAll()
        .Where(func)
        .ToList();
}

It obviosly dirty but the idea is working, with dependecies

    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM