【问题标题】:How to create C# Reflection to Lambda Expression returning boolean如何创建 C# 反射到 Lambda 表达式返回布尔值
【发布时间】:2015-05-08 15:50:38
【问题描述】:

我有一个规范接口和类:

public interface ISpecification<TEntity> where TEntity : class, new()
{
    Expression<Func<TEntity, bool>> SatisfiedBy();
}

public abstract class Specification<TEntity> : ISpecification<TEntity> where TEntity : class, new()
{
    public abstract Expression<Func<TEntity, bool>> SatisfiedBy();
    public static Specification<TEntity> operator &(Specification<TEntity> leftSideSpecification, Specification<TEntity> rightSideSpecification)
    {
        return new AndSpecification<TEntity>(leftSideSpecification, rightSideSpecification);
    }
    public static Specification<TEntity> operator |(Specification<TEntity> leftSideSpecification, Specification<TEntity> rightSideSpecification)
    {
        return new OrSpecification<TEntity>(leftSideSpecification, rightSideSpecification);
    }
    public static Specification<TEntity> operator !(Specification<TEntity> specification)
    {
        return new NotSpecification<TEntity>(specification);
    }
    public static bool operator false(Specification<TEntity> specification)
    {
        return false;
    }
    public static bool operator true(Specification<TEntity> specification)
    {
        return true;
    }
}

public class Table1BySpecification: Specification<Table1>
{
    Propiedades Privadas
    Expression<Func<Table1, bool>> _Expression = null;

    public Table1BySpecification(Expression<Func<Table1, bool>> expression)
    {
        this._Expression = expression;
    }

    public override Expression<Func<Table1, bool>> SatisfiedBy()
    {
        return this._Expression;
    }
}

我创建了一个 Table1BySpecification 以便我可以从一个通用函数运行...

public IEnumerable<TEntity> GetBySpecification(string propertyName, object propertyValue, propertyOperator ){

    ISpecification<Table1> Specification = new Table1BySpecification(t1 => t1.name == "test_name");          
    context.CreateDbSet<Table1>().Where(Specification.SatisfiedBy())
}

这适用于 Table1 实体,但是我想改用 TEntity,并使用反射来使用动态规范。也许我可以有类似的东西:

public IEnumerable<TEntity> GetBySpecification(string propertyName = "name", object propertyValue = "test_name", string propertyOperator = "==" ){

    var source = typeof(TEntity); 
    var t = Expression.Parameter( source, "t" );
    var sourceProperty = Expression.MakeMemberAccess( arg, source.GetProperty( propertyName ) );
    PropertyInfo propertyField = type.GetProperty(propertyName);
    Type propertyType = propertyField.GetType();

    PropertyInfo[] props = typeof(TEntity).GetProperties();
    foreach (PropertyInfo prop in props)
    {
        var displayAttribute = prop.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == propertyType);
        if (displayAttribute != null)
        {
            var parameterExpression = Expression.Parameter(typeof(TEntity), "x");
            var memberExpression = Expression.PropertyOrField(parameterExpression, prop.Name);
            var memberExpressionConversion = Expression.Convert(memberExpression, typeof(object));
            var lambda = Expression.Lambda<Func<TEntity, object>>(memberExpressionConversion, parameterExpression);                    
        }
    }

    ISpecification<TEntity> Specification = new EntityByCustomSpecification<TEntity>(***Reflection_Expression***);

    context.CreateDbSet<TEntity>().Where(Specification.SatisfiedBy()),
}

我不知道这段代码是否可以成为解决方案的一部分,以便至少在 propertyName 变量方面创建 (Reflection_Expression)。 我真的无法将 (Reflection_Expression) 创建为 lambda 表达式并最终获得该 Reflection_Expression 实现...

(t1 => t1.name == "test_name")

...当TEntity为t1时,propertyName为name,其值propertyValue为“test_name”,操作符propertyOperator为“==”

请帮忙???

非常感谢!

【问题讨论】:

    标签: c# linq generics reflection expression


    【解决方案1】:

    给定

    public class EntityByCustomSpecification<TEntity> : Specification<TEntity> where TEntity : class, new()
    {
        Expression<Func<TEntity, bool>> _Expression = null;
    
        public EntityByCustomSpecification(Expression<Func<TEntity, bool>> expression)
        {
            this._Expression = expression;
        }
    
        public override Expression<Func<TEntity, bool>> SatisfiedBy()
        {
            return this._Expression;
        }
    }
    

    (不清楚你是否已经拥有)

    你想要的是:

    public IEnumerable<TEntity> GetBySpecification<TEntity>(object propertyValue, string propertyName = "name", ExpressionType operation = ExpressionType.Equal) where TEntity : class, new()
    {
        ParameterExpression par = Expression.Parameter(typeof(TEntity));
    
        Expression left = Expression.PropertyOrField(par, propertyName);
        Expression right = Expression.Constant(propertyValue, left.Type);
    
        Expression comparison;
    
        try
        {
            comparison = Expression.MakeBinary(operation, left, right);
        }
        catch (InvalidOperationException)
        {
            // string case, for example
            Type icomparable = typeof(IComparable<>).MakeGenericType(left.Type);
    
            if (!left.Type.GetInterfaces().Any(x => x == icomparable))
            {
                throw;
            }
    
            InterfaceMapping interfaceMap = left.Type.GetInterfaceMap(icomparable);
            int ix = Array.FindIndex(interfaceMap.InterfaceMethods, x => x.Name == "CompareTo");
            MethodInfo method = interfaceMap.TargetMethods[ix];
    
            // left.CompareTo(right) [operation] 0
            comparison = Expression.MakeBinary(operation, Expression.Call(left, method, right), Expression.Constant(0));
        }
    
        if (comparison.Type != typeof(bool))
        {
            throw new ArgumentException("operationType");
        }
    
        Expression<Func<TEntity, bool>> lambda = Expression.Lambda<Func<TEntity, bool>>(comparison, par);
    
        ISpecification<TEntity> specification = new EntityByCustomSpecification<TEntity>(lambda);
    
        var result = context.Set<TEntity>().Where(specification.SatisfiedBy());
        return result;
    }
    

    请注意,为了更简单,它接受ExpressionType,而不是string propertyOperator。 ExpressionType 包含所有比较运算符(&lt;、&lt;=、==、&gt;=、&gt;),以及可以忽略的数学运算符(+、-...) .您可以轻松编写一个方法,给定 string 返回正确的 ExpressionType。

    我已更正了可空类型的错误。我通过IComparable&lt;T&gt; 接口添加了对string 的支持。

    【讨论】:

    • 现在应该有什么方法可以让比较表达式与字符串一起使用,因为如果我设置 operation = "Expression.GreaterThan" 并且 propertyValue 是字符串类型...... BinaryExpression比较 = Expression.MakeBinary(操作, 左, 右); .....不起作用
    • @ForumAccount 一个大开关ExpressionType operation; switch (stringop) case "==": operation = ExpressionType.Equal; break; case "&gt;=": operation = ExpressionType.
    • 问题是诸如“GreaterThan”之类的运算符类型不适用于字符串或日期时间...
    • @ForumAccount 对于string,即使在LINQ 中执行x =&gt; x.MyString &gt;= x.MyString 也是无效的。对于DateTime,我应该修复它。 DateTime 不是问题,而是可以为空的字段。对于字符串,您必须执行 x.MyString.CompareTo(x.MyString) &gt;= 0 才能进行 &gt;= 比较。
    • @ForumAccount 添加了对string 的支持。它使用CompareTo
    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2011-12-14
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多