我有一个 IQueryable 扩展方法,用于减少在 EF Core DbContext 模型中搜索多个字段所需的样板代码量:
public static IQueryable<TEntity> WherePropertyIsLikeIfStringIsNotEmpty<TEntity>(this IQueryable<TEntity> query,
string searchValue, Expression<Func<TEntity, string>> propertySelectorExpression)
{
if (string.IsNullOrEmpty(searchValue) || !(propertySelectorExpression.Body is MemberExpression memberExpression))
{
return query;
}
// get method info for EF.Functions.Like
var likeMethod = typeof(DbFunctionsExtensions).GetMethod(nameof(DbFunctionsExtensions.Like), new []
{
typeof(DbFunctions),
typeof(string),
typeof(string)
});
var searchValueConstant = Expression.Constant($"%{searchValue}%");
var dbFunctionsConstant = Expression.Constant(EF.Functions);
var propertyInfo = typeof(TEntity).GetProperty(memberExpression.Member.Name);
var parameterExpression = Expression.Parameter(typeof(TEntity));
var propertyExpression = Expression.Property(parameterExpression, propertyInfo);
var callLikeExpression = Expression.Call(likeMethod, dbFunctionsConstant, propertyExpression, searchValueConstant);
var lambda = Expression.Lambda<Func<TEntity, bool>>(callLikeExpression, …Run Code Online (Sandbox Code Playgroud)