你能教导实体框架识别表达吗?

时间:2014-01-22 15:29:54

标签: c# entity-framework extension-methods

我有一个使用Entity Framework的搜索功能。您可以搜索的其中一项是日期范围。您可能会说“SearchStart和Search End之间的开始日期”。使用linq语法编写并不困难,但是当您有许多不同的日期参数可供搜索时,它会变得非常冗长。

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

正如我所料,使用扩展方法会抛出异常: “LINQ to Entities无法识别方法'布尔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);
 }

3 个答案:

答案 0 :(得分:6)

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

我们没有教导实体框架如何读取新表达式,而是将表达式中的表达式分解为实体框架已经知道如何读取的内容。

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 => date >= start && date < end,并将其传递给转换器以映射必要的列。您需要在原始lambada中为每个参数传递一个映射。

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作为参数传入。

答案 1 :(得分: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;
}

答案 2 :(得分:0)

您可以使用DbFunctions类生成BETWEEN sql语句

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

在早于6.0的EF版本中称为EntityFunctions