首页> C#>如何在提供IQueryable输出的LINQ查询中使用Func
作者:互联网
我提供了以下查询(简化版本)以从我的服务返回IQueryable:
var query =
(from item in _entityRepository.DbSet()
where
MyCondition
orderby Entity.EntityID descending
select new DTOModel
{
Id = Entity.EntityID,
...,
//My problem is here, when I trying to call a function into linq query:
//Size = Entity.IsPersian ? (Entity.EntitySize.ConvertNumbersToPersian()) : (Entity.EntitySize)
//Solution (1):
//Size = ConvertMethod1(Entity)
//Solution (2):
//Size = ConvertMethod2(Entity)
});
根据查询,在服务类中还有以下代码:
//Corresponding to solution (1):
Func<Entity, string> ConvertMethod1 = p => (p.IsPersian ? p.EntitySize.ConvertNumbersToPersian() : p.EntitySize);
//Corresponding to solution (2):
Expression<Func<Entity, string>> ConvertMethod2 = (p) => (p.IsPersian ? p.EntitySize.ConvertNumbersToPersian() : p.EntitySize);
我已经看到以下错误:
产生的对应于解决方案(1)的错误:
LINQ to Entities不支持LINQ表达式节点类型’Invoke’.
产生的对应于解决方案(2)的错误:
其编译错误:
方法,委托或事件是预期的
非常感谢您的任何高级帮助.
解决方法:
这实际上是由IQueryable<>公开的leaky abstraction.与ORM结合使用.
第一次尝试将在内存中执行时影响工作.但是,使用ORM并非如此.您的第一个代码无法与LINQ实体一起使用的原因是Func<>.是已编译的代码.它不表示可以轻松转换为SQL的表达式树.
第二次尝试是自然尝试的解决方案,但由于将代码转换为表达式树而进行了某种神奇的转换,因此失败了.在编写选择项时,并不是针对Expression对象进行编码.但是当您编译代码时; C#将自动将其转换为表达式树.不幸的是,没有办法轻松地将实际的Expression项添加到组合中.
您需要的是:
>占位符函数,用于获取对您的表达式的引用
>如果要将查询发送到ORM,则使用表达式树重写器.
您最终得到的查询类似于:
Expression<Func<Person, int>> personIdSelector = person => person.PersonID;
var query = Persons
.Select(p =>
new {
a = personIdSelector.Inline(p)
})
.ApplyInlines();
使用以下表达帮助器:
public static class ExpressionExtensions
{
public static TT Inline<T, TT>(this Expression<Func<T, TT>> expression, T item)
{
// This will only execute while run in memory.
// LINQ to Entities / EntityFramework will never invoke this
return expression.Compile()(item);
}
public static IQueryable<T> ApplyInlines<T>(this IQueryable<T> expression)
{
var finalExpression = expression.Expression.ApplyInlines().InlineInvokes();
var transformedQuery = expression.Provider.CreateQuery<T>(finalExpression);
return transformedQuery;
}
public static Expression ApplyInlines(this Expression expression) {
return new ExpressionInliner().Visit(expression);
}
private class ExpressionInliner : ExpressionVisitor
{
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.Name == "Inline" && node.Method.DeclaringType == typeof(ExpressionExtensions))
{
var expressionValue = (Expression)Expression.Lambda(node.Arguments[0]).Compile().DynamicInvoke();
var arg = node.Arguments[1];
var res = Expression.Invoke(expressionValue, arg);
return res;
}
return base.VisitMethodCall(node);
}
}
}
// https://codereview.stackexchange.com/questions/116530/in-lining-invocationexpressions/147357#147357
public static class ExpressionHelpers
{
public static TExpressionType InlineInvokes<TExpressionType>(this TExpressionType expression)
where TExpressionType : Expression
{
return (TExpressionType)new InvokeInliner().Inline(expression);
}
public static Expression InlineInvokes(this InvocationExpression expression)
{
return new InvokeInliner().Inline(expression);
}
public class InvokeInliner : ExpressionVisitor
{
private Stack<Dictionary<ParameterExpression, Expression>> _context = new Stack<Dictionary<ParameterExpression, Expression>>();
public Expression Inline(Expression expression)
{
return Visit(expression);
}
protected override Expression VisitInvocation(InvocationExpression e)
{
var callingLambda = e.Expression as LambdaExpression;
if (callingLambda == null)
return base.VisitInvocation(e);
var currentMapping = new Dictionary<ParameterExpression, Expression>();
for (var i = 0; i < e.Arguments.Count; i++)
{
var argument = Visit(e.Arguments[i]);
var parameter = callingLambda.Parameters[i];
if (parameter != argument)
currentMapping.Add(parameter, argument);
}
if (_context.Count > 0)
{
var existingContext = _context.Peek();
foreach (var kvp in existingContext)
{
if (!currentMapping.ContainsKey(kvp.Key))
currentMapping[kvp.Key] = kvp.Value;
}
}
_context.Push(currentMapping);
var result = Visit(callingLambda.Body);
_context.Pop();
return result;
}
protected override Expression VisitParameter(ParameterExpression e)
{
if (_context.Count > 0)
{
var currentMapping = _context.Peek();
if (currentMapping.ContainsKey(e))
return currentMapping[e];
}
return e;
}
}
}
这将允许您在到达ORM之前重新编写表达式树,从而使表达式直接内联到树中.
标签:func,iqueryable,linq,c 来源: https://codeday.me/bug/20191025/1929116.html