【问题标题】:Can you teach Entity Framework to recognize an expression?你能教 Entity Framework 识别表达式吗?
【发布时间】:2014-01-22 15:29:54
【问题描述】:

我有一个使用实体框架的搜索功能。您可以搜索的其中一件事是日期范围。您可能会说“开始日期在 SearchStart 和 Search End 之间”。用 linq 语法编写起来并不难,但是当您有许多不同的日期参数要搜索时,它会变得非常冗长。

我在 DateTime 上有一个扩展方法,它基本上检查日期包含在 StartDate 和 EndDate 之间。我在 EF 不是问题的其他地方使用它,但我也想将它与 EF 查询一起使用。我通过在执行 ToList 之前应用额外的 WHERE 子句来动态创建查询(它将尝试运行查询)。

正如我所料,使用扩展方法会引发异常: “LINQ to Entities 无法识别方法 'Boolean IsBetween(System.DateTime, System.DateTime, System.DateTime)' 方法,并且此方法无法转换为存储表达式。”

我知道 Linq to Entities 无法知道 IsBetween 在 Sql 中的翻译,但我有办法给它指示吗?我尝试在网上搜索答案,但没有多大帮助。如果有一些属性我可以添加到扩展方法中,或者我可以通过某种方式更新 EF 配置?

我猜不是,但我不想不问就假设。

谢谢!

更新:添加扩展方法代码

 public static bool IsBetween(this DateTime date , DateTime start, DateTime end)
 {
   return (date >= start && date < end);
 }

【问题讨论】:

  • 使用单独的 > 和
  • 只要在 .Where 子句中使用表达式之前将子句定义为表达式,就应该可以做到。在此处发布您的 IsBetween 扩展方法,应该有人可以帮助您。
  • 已更新代码。谢谢!
  • 你可以在方法中创建一个表达式或者简单的 Func 然后在查询中使用它。
  • 你能给我一个快速的样本吗? IsBetween 返回类型会是 Func 吗?

标签: c# entity-framework extension-methods


【解决方案1】:

这是一个完全通用的方法,similar to what danludig's answer is doing,但更深入地研究并手动构建表达式树以使其工作。

我们不是在教 Entity Framework 如何读取新的表达式,而是将表达式分解为其组成部分,使其成为 Entity Framework 已经知道如何读取的内容。

public static IQueryable<T> IsBetween<T>(this IQueryable<T> query, Expression<Func<T, DateTime>> selector, DateTime start, DateTime end)
{
    //Record the start time and end time and turn them in to constants to be passed in to the query.
    //There may be a better way to pass them as parameters instead of constants but I don't have the skill with expression trees to know how to do it.
    var startTime = Expression.Constant(start);
    var endTime = Expression.Constant(end);

    //We get the body of the expression that was passed in that selects the DateTime column in the row for us.
    var selectorBody = selector.Body;

    //We need to pass along the parametres from that original selector.
    var selectorParameters = selector.Parameters;

    // Represents the "date >= start"
    var startCompare = Expression.GreaterThanOrEqual(selectorBody, startTime);

    // Represents the "date < end"
    var endCompare = Expression.LessThan(selectorBody, endTime);

    // Represents the "&&" between the two statements.
    var combinedExpression = Expression.AndAlso(startCompare, endCompare);

    //Reform the new expression in to a lambada to be passed along to the Where clause.
    var lambada = Expression.Lambda<Func<T, bool>>(combinedExpression, selectorParameters);

    //Perform the filtering and return the filtered query.
    return query.Where(lambada);
}

生成如下 SQL

SELECT 
    [Extent1].[TestId] AS [TestId], 
    [Extent1].[Example] AS [Example]
    FROM [dbo].[Tests] AS [Extent1]
    WHERE ([Extent1].[Example] >= convert(datetime2, '2013-01-01 00:00:00.0000000', 121)) AND ([Extent1].[Example] < convert(datetime2, '2014-01-01 00:00:00.0000000', 121))

使用下面这个程序。

private static void Main(string[] args)
{
    using (var context = new TestContext())
    {
        context.SaveChanges();

        context.Tests.Add(new Test(new DateTime(2013, 6, 1)));
        context.Tests.Add(new Test(new DateTime(2014, 6, 1)));
        context.SaveChanges();

        DateTime start = new DateTime(2013, 1, 1);
        DateTime end = new DateTime(2014, 1, 1);

        var query = context.Tests.IsBetween(row => row.Example, start, end);

        var traceString = query.ToString();

        var result = query.ToList();

        Debugger.Break();
    }
}

public class Test
{
    public Test()
    {
        Example = DateTime.Now;
    }

    public Test(DateTime time)
    {
        Example = time;
    }

    public int TestId { get; set; }
    public DateTime Example { get; set; }
}

public class TestContext : DbContext
{
    public DbSet<Test> Tests { get; set; } 
}

这是一个实用程序,可以转换通用表达式并将其映射到您的特定对象。这允许您将表达式编写为 date =&gt; date &gt;= start &amp;&amp; date &lt; end 并将其传递给转换器以映射必要的列。您需要在原始 lambda 中为每个参数传入一个映射。

public static class LambadaConverter
{
    /// <summary>
    /// Converts a many parametered expression in to a single paramter expression using a set of mappers to go from the source type to mapped source.
    /// </summary>
    /// <typeparam name="TNewSourceType">The datatype for the new soruce type</typeparam>
    /// <typeparam name="TResult">The return type of the old lambada return type.</typeparam>
    /// <param name="query">The query to convert.</param>
    /// <param name="parameterMapping">The mappers to go from the single source class to a set of </param>
    /// <returns></returns>
    public static Expression<Func<TNewSourceType, TResult>>  Convert<TNewSourceType, TResult>(Expression query, params Expression[] parameterMapping)
    {
        //Doing some pre-condition checking to make sure everything was passed in correctly.
        var castQuery = query as LambdaExpression;

        if (castQuery == null)
            throw new ArgumentException("The passed in query must be a lambada expression", "query");

        if (parameterMapping.Any(expression => expression is LambdaExpression == false) ||
            parameterMapping.Any(expression => ((LambdaExpression)expression).Parameters.Count != 1) ||
            parameterMapping.Any(expression => ((LambdaExpression)expression).Parameters[0].Type != typeof(TNewSourceType)))
        {
            throw new ArgumentException("Each pramater mapper must be in the form of \"Expression<Func<TNewSourceType,TResut>>\"",
                                        "parameterMapping");
        }

        //We need to remap all the input mappings so they all share a single paramter variable.
        var inputParameter = Expression.Parameter(typeof(TNewSourceType));

        //Perform the mapping-remapping.
        var normlizer = new ParameterNormalizerVisitor(inputParameter);
        var mapping = normlizer.Visit(new ReadOnlyCollection<Expression>(parameterMapping));

        //Perform the mapping on the expression query.
        var customVisitor = new LambadaVisitor<TNewSourceType, TResult>(mapping, inputParameter);
        return (Expression<Func<TNewSourceType, TResult>>)customVisitor.Visit(query);

    }

    /// <summary>
    /// Causes the entire series of input lambadas to all share the same 
    /// </summary>
    private class ParameterNormalizerVisitor : ExpressionVisitor
    {
        public ParameterNormalizerVisitor(ParameterExpression parameter)
        {
            _parameter = parameter;
        }

        private readonly ParameterExpression _parameter;

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if(node.Type == _parameter.Type)
                return _parameter;
            else
                throw new InvalidOperationException("Was passed a parameter type that was not expected.");
        }
    }

    /// <summary>
    /// Rewrites the output query to use the new remapped inputs.
    /// </summary>
    private class LambadaVisitor<TSource,TResult> : ExpressionVisitor
    {
        public LambadaVisitor(ReadOnlyCollection<Expression> parameterMapping, ParameterExpression newParameter)
        {
            _parameterMapping = parameterMapping;
            _newParameter = newParameter;
        }

        private readonly ReadOnlyCollection<Expression> _parameterMapping;
        private readonly ParameterExpression _newParameter;

        private ReadOnlyCollection<ParameterExpression> _oldParameteres = null;

        protected override Expression VisitParameter(ParameterExpression node)
        {
            //Check to see if this is one of our known parameters, and replace the body if it is.
            var index = _oldParameteres.IndexOf(node);
            if (index >= 0)
            {
                return ((LambdaExpression)_parameterMapping[index]).Body;
            }

            //Not one of our known parameters, process as normal.
            return base.VisitParameter(node);
        }

        protected override Expression VisitLambda<T>(Expression<T> node)
        {
            if (_oldParameteres == null)
            {
                _oldParameteres = node.Parameters;

                var newBody = this.Visit(node.Body);

                return Expression.Lambda<Func<TSource, TResult>>(newBody, _newParameter);
            }
            else
                throw new InvalidOperationException("Encountered more than one Lambada, not sure how to handle this.");
        }
    }
}

这是一个我用来测试它的简单测试程序,它会生成格式良好的查询,并将参数传入它们应该在的位置。

    private static void Main(string[] args)
    {
        using (var context = new TestContext())
        {
            DateTime start = new DateTime(2013, 1, 1);
            DateTime end = new DateTime(2014, 1, 1);

            var query = context.Tests.IsBetween(row => row.Example, start, end);
            var traceString = query.ToString(); // Generates the where clause: WHERE ([Extent1].[Example] >= @p__linq__0) AND ([Extent1].[Example] < @p__linq__1)

            var query2 = context.Tests.ComplexTest(row => row.Param1, row => row.Param2);
            var traceString2 = query2.ToString(); //Generates the where clause: WHERE (N'Foo' = [Extent1].[Param1]) AND ([Extent1].[Param1] IS NOT NULL) AND (2 = [Extent1].[Param2])

            Debugger.Break();
        }
    }

    public class Test
    {
        public int TestId { get; set; }
        public DateTime Example { get; set; }
        public string Param1 { get; set; }
        public int Param2 { get; set; }
    }

    public class TestContext : DbContext
    {
        public DbSet<Test> Tests { get; set; } 
    }

    public static IQueryable<T> IsBetween<T>(this IQueryable<T> query, Expression<Func<T, DateTime>> dateSelector, DateTime start, DateTime end)
    {
        Expression<Func<DateTime, bool>> testQuery = date => date >= start && date < end;

        var newQuery = LambadaConverter.Convert<T, bool>(testQuery, dateSelector);

        return query.Where(newQuery);
    }

    public static IQueryable<T> ComplexTest<T>(this IQueryable<T> query, Expression<Func<T, string>> selector1, Expression<Func<T, int>> selector2)
    {
        Expression<Func<string, int, bool>> testQuery = (str, num) => str == "Foo" && num == 2;

        var newQuery = LambadaConverter.Convert<T, bool>(testQuery, selector1, selector2);

        return query.Where(newQuery);
    }

您可以看到这也解决了我在第一个示例中遇到的“常量字符串”问题,DateTimes 现在作为参数传入。

【讨论】:

  • 目前还不是大师,我会说初学者到中介。我不知道如何使开始时间和结束时间成为参数而不是常量(如果有人知道如何随意编辑!)
  • 我打算明天早上试试。看起来这可能是我需要的!谢谢!我会告诉你进展如何。
  • @danludwig 好的,现在我正在进入 Guru 领域。
  • 哇,效果很好!我总是很欣赏非常详细的解释。我也从你那里学到了很多关于表达式的知识。如果我可以 +2 你我会的。谢谢!
【解决方案2】:

用法:

var start = new DateTime(2014, 01, 21);
var end = new DateTime(2014, 01, 22);
var queryable = dbContext.Set<MyEntity>();
queryable = queryable.InBetween(start, end);

扩展方法

public static class EntityExtensions
{
    public static IQueryable<MyEntity> InBetween(this IQueryable<MyEntity> queryable,
        DateTime start, DateTime end)
    {
        return queryable.Where(x => x.DateColumn >= start && x.DateColumn < end);
    }
}

现在您无法在此处完全重用您的其他扩展方法。但是,您可以在其他几个查询中重用这个新的扩展方法。只需在您的可查询对象上调用 .InBetween 并传递参数。

这是另一种方法:

public static IQueryable<MyEntity> InBetween(this IQueryable<MyEntity> queryable,
    DateTime start, DateTime end)
{
    return queryable.Where(InBetween(start, end));
}

public static Expression<Func<MyEntity, bool>> InBetween(DateTime start,
    DateTime end)
{
    return x => x.DateColumn >= start && x.DateColumn < end;
}

【讨论】:

  • 好的,如果我提供实体类型并使用特定的字段/属性,我可以做到,但它不能完全通用。这就说得通了。感谢您的代码!
  • 您可以对实现接口的实体类进行通用操作。例如,假设您有IDateSpanEntity { DateTime Start {get;} DateTime End {get;}},您可以针对该接口编写扩展方法,然后在多个实体中实现该接口。您也可以通过查看@Jakub Konecki 的 DbFunctions 来使其更通用。
  • @danludwig 如果您想查看通用植入,请查看我的回答,我和您做的事情几乎相同,但实际上闯入构建表达式树并使用传入的表达式作为选择器.
【解决方案3】:

可以使用DbFunctions类生成BETWEENsql语句

http://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions(v=vs.113).aspx

在 6.0 之前的 EF 版本中称为 EntityFunctions

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2011-04-03
    • 2016-03-28
    • 1970-01-01
    • 2012-02-02
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    相关资源
    最近更新 更多