gpt4 book ai didi

c# - 你能教 Entity Framework 识别表达式吗?

转载 作者:行者123 更新时间:2023-11-30 19:41:02 25 4
gpt4 key购买 nike

我有一个使用 Entity Framework 的搜索功能。您可以搜索的其中一项内容是日期范围。您可能会说“开始日期介于 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);
}

最佳答案

这是一个完全通用的方法,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 => 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 现在作为参数传入。

关于c# - 你能教 Entity Framework 识别表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21287111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com