Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

c# 4.0 - Convert Linq to Sql Expression to Expression Tree

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...