linq-to-sql – 将Linq转换为Sql表达式到表达式树

前端之家收集整理的这篇文章主要介绍了linq-to-sql – 将Linq转换为Sql表达式到表达式树前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
任何人都可以将这个简单的LINQ-to-sql转换为表达式树:
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,请执行以下操作:

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

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

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

猜你在找的MsSQL相关文章