本文介绍了将 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();

推荐答案

应该这样做:

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 执行以下操作:

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 表达式转换为表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:25