将Linq转换为Sql表达式到表达式树 [英] Convert Linq to Sql Expression to Expression Tree

查看:186
本文介绍了将Linq转换为Sql表达式到表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以将这个简单的LINQ to SQL转换为表达式树:

Can anyone convert this simple LINQ-to-SQL to an Expression Tree:

List<Region> lst = (from r in dc.Regions
                    where r.RegionID > 2 && r.RegionDescription.Contains("ern")
                    select r).ToList();


推荐答案


$ b

This should do it:

var query = dc.Regions.AsQueryable();

ParameterExpression pe = Expression.Parameter(typeof(Region), "region");

Expression id = Expression.PropertyOrField(pe, "RegionID");
Expression two = Expression.Constant(2);
Expression e1 = Expression.GreaterThan(id, two);

Expression description = Expression.PropertyOrField(pe, "RegionDescription");
MethodInfo method = typeof(string).GetMethod("Contains", new[] {typeof(string)});
Expression ern = Expression.Constant("ern",typeof(string));
Expression e2 = Expression.Call(description, method, ern);

Expression e3 = Expression.And(e1, e2);

MethodCallExpression whereCallExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new Type[] { query.ElementType },
                query.Expression,
                Expression.Lambda<Func<Region, bool>>(e3, new ParameterExpression[] { pe }));
var results = query.Provider.CreateQuery<Region>(whereCallExpression);

List<Region> lst = results.ToList();

并从结果中选择 RegionID set

And to select just RegionID from the result set do the following:

MethodCallExpression selectExpression = Expression.Call(
                                typeof(Queryable),                                
                                "Select",
                                new[]{ typeof(Region), typeof(int)},
                                whereCallExpression, 
                                Expression.Lambda<Func<Region, int>>(id, pe));

var regionIDsQuery = query.Provider.CreateQuery<int>(selectExpression);

List<int> regionIDs = regionIDsQuery.ToList();

这篇关于将Linq转换为Sql表达式到表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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