如何重载 LINQ IQueryable<TEntity> Where() 以接受列名

How do I overload LINQ IQueryable<TEntity> Where() to accept column name

我想修改以下内容以接受将在 Where 方法中搜索的列名,例如:

        public TEntity GetEntity(int val)
        {
            TEntity entity = _DbContext.Set<TEntity>()
                   .Where(e => e.Id == val)
                   .FirstOrDefault();
            return entity;
        }

改为

        public TEntity GetEntity(int val, string colName)
        {
            TEntity entity = _DbContext.Set<TEntity>()
                   .WhereWithColName(val, colName)
                   .FirstOrDefault();
            return entity;
        }

表达式树对我来说还是太复杂了...

好的,解决了:

public static IQueryable<TEntity> WhereById<TEntity, TKey>(this IQueryable<TEntity> query, TKey value, string colName)
            where TEntity : class
{
    var param = Expression.Parameter(typeof(TEntity), "e");
    var propAccess = Expression.PropertyOrField(param, colName);
    var valExpr = Expression.Constant(value);

    var predicate = Expression.Equal(propAccess,valExpr);

    var predicateLambda = Expression.Lambda<Func<TEntity, bool>>(predicate, param);

    return query.Where(predicateLambda);
}

然后调用函数是:

public TEntity GetEntity(int val, string colName)
{
    TEntity entity = _DbContext.Set<TEntity>()
           .WhereById<TEntity, int>(val, colName)
           .FirstOrDefault();
    return entity;
}