微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何为可空属性如 Nullable<Int32>

如何解决如何为可空属性如 Nullable<Int32>

我在生成用于 EF Core 查询的动态函数时遇到问题。

这是函数生成

public static Expression<Func<TEntity,bool>> WhereFunc<TEntity>(this string propertyName,object? propertyValue)
        where TEntity : class,IEntity
{
    var info = typeof(TEntity).GetProperty(propertyName);
    var parameter = Expression.Parameter(typeof(TEntity),$"{nameof(TEntity).Substring(0,2)}");
    var property = Expression.Property(parameter,propertyName);
    var value = Expression.Constant(propertyValue);
    var clause = Expression.Equal(property,Expression.Constant(propertyValue));
    return Expression.Lambda<Func<TEntity,bool>>(clause,parameter);
}

这是所有属性需要的动态查询生成

public static IQueryable<TEntity> SetWhere<TEntity,TSearch>(this IEnumerable<TEntity> 
 entities,IEnumerable<PropertyInfo> fields,TSearch entity)
        where TEntity : class,IEntity
        where TSearch : class,ISearchEntity
{
     var query = entities.AsQueryable();

     if (fields != null && fields.Any())
         foreach (var item in fields)
             query = query.Where(EntityFuncs.WhereFunc<TEntity>(item.Name,item.GetValue(entity)));

     return query;
}

这是我使用它的代码

var query = Entities
              .Skip(filter.Total)
              .Take(filter.More)
              .AsQueryable();
query = query.SetWhere<TEntity,TSearchEntity>(properties,filter.Entity);

对于字符串属性,它可以正常工作。

但在 nullable<int> 属性的示例中,我收到此错误

未为类型“System.Nullable`1[system.int32]”和“system.int32”定义二元运算符 Equal

解决方法

您必须显式测试 propertyValue 的类型或属性的类型,并相应地调用 Nullable.Equals

如果给定类型是 Nullable.GetUnderlyingType 构造的类型(例如 int),

Nullable<> 将返回不可为空的底层类型(例如 int?);否则将返回 null

public static Expression<Func<TEntity,bool>> WhereFunc<TEntity>(this string propertyName,object? propertyValue)
    where TEntity : class,IEntity
{
    var info = typeof(TEntity).GetProperty(propertyName);
    var parameter = Expression.Parameter(typeof(TEntity),$"{nameof(TEntity).Substring(0,2)}");
    var property = Expression.Property(parameter,propertyName);
    var value = Expression.Constant(propertyValue);

    var propertyType = info?.PropertyType ?? propertyValue?.GetType();
    var underlyingType = propertyType is not null ? Nullable.GetUnderlyingType(propertyType) : null;

    Expression clause;
    if (underlyingType is not null)
    {
        var methodOpen = typeof(Nullable).GetMethod(nameof(Nullable.Equals),BindingFlags.Static | BindingFlags.Public);
        var method = methodOpen.MakeGenericMethod(underlyingType);
        clause = Expression.Call(method,property,Expression.Convert(value,propertyType));
    }
    else
    {
        clause = Expression.Equal(property,value);
    }

    return Expression.Lambda<Func<TEntity,bool>>(clause,parameter);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。