将Linq转换为Sql表达式到表达式树

时间:2011-03-07 21:23:00

标签: linq-to-sql c#-4.0 expression expression-trees

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

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

1 个答案:

答案 0 :(得分:5)

这应该这样做:

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, 
                                Expression.Lambda<Func<Region, int>>(id, pe));

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

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