如何使用非通用Lambda产生子查询 [英] How to produce a Subquery using non-generic Lambda

查看:73
本文介绍了如何使用非通用Lambda产生子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何将以下通用Lambda函数转换为lambda表达式:

How would you translate the following generic Lambda function into a lambda expression :

context.AssociateWith<Product>(p => p.Regions.Where(r => r.Country == 'Canada')

我正在尝试创建一个完整的lambda表达式,而没有任何<T>或直接调用.像这样的东西:

I'm trying to create a full lambda expression without any <T> or direct call. Something like :

void AddFilter(ITable table, MetaDataMember relation)
{
    var tableParam = Expression.Parameter(table.ElementType, "e");
    var prop = Expression.Property(tableParam, relation.Name);
    var func = typeof(Func<,>).MakeGenericType(table.ElementType, relation.type)
    var exp = Expression.Lambda(func, prop, tableParam);
}

这将产生e.Regions ...但是我无法从那里得到Where部分...

This will produce e.Regions... but I'm unable to get the Where part from there...

推荐答案

我知道我的答案已经很晚了,可能这不是您要寻找的确切解决方案(仍然经常使用),但是也许它将帮助您和其他人建立他们的表达方式:

I know I'm very late in the game with my answer and likely this is not the exact solution you are looking for (still uses the frequently), but maybe it will help you and others building their expression:

/* 
example: Session.Query.Where(m => m.Regions.Where(f => f.Name.Equals("test")))
*/ 

var innerItem = Expression.Parameter(typeof(MyInnerClass), "f");
var innerProperty = Expression.Property(innerItem, "Name");
var innerMethod = typeof(string).GetMethod("Equals", new[] { typeof(string) });
var innerSearchExpression = Expression.Constant(searchString, typeof(string));
var innerMethodExpression = Expression.Call(innerProperty, innerMethod, new[] { innerSearchExpression });
var innerLambda = Expression.Lambda<Func<MyInnerClass, bool>>(innerMethodExpression, innerItem);

var outerItem = Expression.Parameter(typeof(MyOuterClass), "m");
var outerProperty = Expression.Property(outerItem, info.Name);
/* calling a method extension defined in Enumerable */
var outerMethodExpression = Expression.Call(typeof(Enumerable), "Where", new[] { typeof(MyInnerClass) }, outerProperty, innerLambda);
var outerLambda = Expression.Lambda<Func<MyOuterClass, bool>>(outerMethodExpression, outerItem);
query = query.Where(outerLambda);

基于此处发布的答案:创建动态包含以下内容的Linq表达式子查询.

Based on an answer posted here: Creating a Linq expression dynamically containing a subquery.

这篇关于如何使用非通用Lambda产生子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆