拉开表达式<Func <T,object >>

Sam*_*ngh 6 c# extension-methods dapper

我正忙于在DapperDapperExtensions之上创建包装器扩展方法.目前我正在尝试向GetList<T>扩展方法添加过滤,类似于LINQ的Where<T>扩展方法.我已经看到了这个问题,但似乎我无法实现Marc Gravell所建议的,因为EqualsExpression.NET 4.5中没有类型.这是一些演示代码,以帮助解释我的问题:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq.Expressions;
using DapperExtensions;

namespace Dapper.Extensions.Demo
{
    public class Program
    {
        private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["DapperDbContext"].ConnectionString;
        public static IDbConnection Connection { get { return new SqlConnection(ConnectionString); } }

        public static void Main(string[] args)
        {
            const int marketId = 2;
            var matchingPeople = Connection.Get<Person>(p => p.MarketId, marketId); // This works

            // Below is a LambdaExpression. expression.Body is, bizarrely, a UnaryExpression with a Convert
            //var matchingPeople = Connection.Get<Person>(p => p.MarketId == marketId); // Does not work

            foreach (var person in matchingPeople)
            {
                Console.WriteLine(person);
            }

            if (Debugger.IsAttached)
                Console.ReadLine();
        }
    }

    public static class SqlConnectionExtensions
    {
        public static IEnumerable<T> Get<T>(this IDbConnection connection, Expression<Func<T, object>> expression, object value = null) where T : class
        {
            using (connection)
            {
                connection.Open();

                // I want to be able to pass in: t => t.Id == id then:
                // Expression<Func<T, object>> expressionOnLeftOfFilterClause = t => t.Id;
                // string operator = "==";
                // object valueFromLambda = id;
                // and call Predicates.Field(expressionOnLeftOfFilterClause, Operator.Eq, valueFromLambda)

                var predicate = Predicates.Field(expression, Operator.Eq, value);
                var entities = connection.GetList<T>(predicate, commandTimeout: 30);
                connection.Close();
                return entities;
            }
        }
    }

    public class Person
    {
        public int Id { get; set; }

        public string FirstName { get; set; }

        public string Surname { get; set; }

        public int MarketId { get; set; }

        public override string ToString()
        {
            return string.Format("{0}: {1}, {2} - MarketId: {3}", Id, Surname, FirstName, MarketId);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要特别注意我的Get<T>扩展方法:当我通过在任一p => p.MarketIdp => p.MarketId == marketId,expression.Body是类型UnaryExpression.对于后者,expression.Body实际上包含{Convert((p.MarketId == 2))}.

尝试

var binaryExpression = expression as BinaryExpression;
Run Code Online (Sandbox Code Playgroud)

回报null,因为有这是不幸LeftRight性质,我可以找到有用的.

那么,有谁知道如何实现我想要的?接下来,我希望能够Operator根据传入的lambda表达式选择枚举.任何帮助都将非常感激.

Sam*_*ngh 5

我已经想出如何实现我想要的.

综上所述:

  1. 我需要一个包装DapperExtension GetList<T>扩展方法的扩展方法.
  2. 后者可以采用类型的谓词IFieldPredicate,我可以使用它来为要执行的SQL查询添加过滤器.我可以通过使用来实现这一点Predicates.Field<T>(Expression<Func<T, object>> expression, Operator op, object value).
  3. 问题在于将简单的lambda表达式t => t.Id == id转换为参数Predicates.Field<T>.所以,从概念上讲,我需要lambda表达式拉开分为三个部分:t => t.Id,Operator.Eq,和id.

在@ Iridium,@ Eduard和@Jon的帮助下,我的最终解决方案是:

public static class SqlConnectionExtensions
{
    public static IEnumerable<T> Get<T>(this IDbConnection connection, Expression<Func<T, object>> expression) where T : class
    {
        using (connection)
        {
            connection.Open();

            var binaryExpression = (BinaryExpression)((UnaryExpression) expression.Body).Operand;

            var left = Expression.Lambda<Func<T, object>>(Expression.Convert(binaryExpression.Left, typeof(object)), expression.Parameters[0]);
            var right = binaryExpression.Right.GetType().GetProperty("Value").GetValue(binaryExpression.Right);
            var theOperator = DetermineOperator(binaryExpression);

            var predicate = Predicates.Field(left, theOperator, right);
            var entities = connection.GetList<T>(predicate, commandTimeout: 30);

            connection.Close();
            return entities;
        }
    }

    private static Operator DetermineOperator(Expression binaryExpression)
    {
        switch (binaryExpression.NodeType)
        {
            case ExpressionType.Equal:
                return Operator.Eq;
            case ExpressionType.GreaterThan:
                return Operator.Gt;
            case ExpressionType.GreaterThanOrEqual:
                return Operator.Ge;
            case ExpressionType.LessThan:
                return Operator.Lt;
            case ExpressionType.LessThanOrEqual:
                return Operator.Le;
            default:
                return Operator.Eq;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在可以这样做:

var matchingPeople = Connection.Get<Person>(p => p.MarketId == marketId);
Run Code Online (Sandbox Code Playgroud)

我知道这有多么脆弱 - 如果我传入任何更复杂的东西,或者甚至是看起来相同的东西,它会破裂var matchingPeople = Connection.Get<Person>(p => p.MarketId.Equals(marketId));.它确实解决了我90%的情况,所以我很满足于保持原样.