Конвертировать выражение Linq в Sql в дерево выражений - PullRequest
0 голосов
/ 08 марта 2011

Может ли кто-нибудь преобразовать этот простой LINQ-to-SQL в дерево выражений:

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

1 Ответ

5 голосов
/ 08 марта 2011

Это должно сделать это:

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();
...