如何为泛型类型添加表达式?

时间:2015-09-09 10:14:06

标签: c# linq expression

我需要检查geenric服务中的实体,如果它是实体类型,我应该添加动态表达式.Where("IsDeleted==false");

var result = _entityRepo.All();

var isEntityType = typeof(Entity).IsAssignableFrom(typeof(T));
if (isEntityType)
{
    var expression = CreateExpression("IsDeleted", true);
    var casted = (Expression<Func<T, bool>>)expression;
    result = result.Where(casted);
}
return result;

_entityRepoGenericRepository<T>

public static Expression CreateExpression(string propertyName, bool valueToCompare)
{
    // get the type of entity
    var entityType = typeof(Entity);
    // get the type of the value object
    var entityProperty = entityType.GetProperty(propertyName);

    // Expression: "entity"
    var parameter = Expression.Parameter(entityType, "entity");

    // check if the property type is a value type
    // only value types work
    // Expression: entity.Property == value
    return Expression.Equal(
        Expression.Property(parameter, entityProperty),
        Expression.Constant(valueToCompare)
    );
}

当然我在演员表上收到错误:

  

无法投射类型的对象   &#39; System.Linq.Expressions.LogicalBinaryExpression&#39;输入   &#39; {System.Linq.Expressions.Expression {1}} 2 [MadCloud.Domain.Auditing.AuditCategory,System.Boolean]]&#39;

1 个答案:

答案 0 :(得分:1)

假设IsDeleted是实体类型的一部分,只需转换为它:

IEnumerable<T> result = _entityRepo.All();
bool isEntityType = typeof(Entity).IsAssignableFrom(typeof(T));
if (isEntityType)
{
    result = result.Where(x => ((Entity)(object)x).IsDeleted == true);
}
return result;

毕竟,您知道Entity可以从T分配,因此您可以进行投射。请注意,您需要先将其强制转换为object,以便在编译时禁用编译器的类型检查。另请参阅this answer