我从这个问题中汲取灵感:
Convert Linq to Sql Expression to Expression Tree
原始海报询问如何将其转换为表达式树并得到一个很好的答案,可以在上面的链接中看到。
List<Region> lst = (from r in dc.Regions
where r.RegionID > 2 && r.RegionDescription.Contains("ern")
select r).ToList();
如何使用get方法创建一个返回使用ExpressionTree的bool的属性?我希望能够做到这样的事情(显然我不需要== true
):
List<Region> lst = (from r in dc.Regions
where (r.AwesomeProperty == true)
select r).ToList();
我如何定义AwesomeProperty
?
答案 0 :(得分:1)
您可以像LINQ to SQL对象上的任何其他属性一样定义AwesomeProperty
。假设它被键入为bool
(因为您将其与true
进行比较),您将构建Where
查询,如下所示:
// Build the parameter to the where clause predicate and access AwesomeProperty
var regionParameter = Expression.Parameter(typeof(Region), "region");
var awesomeProperty = Expression.Property(regionParameter, "AwesomeProperty");
// Build the where clause predicate using the AwesomeProperty access
var predicate = Expression.Lambda<Func<Region, bool>>(awesomeProperty);
// Get the table, which serves as the base query
var table = dc.Regions.AsQueryable();
// Call the Where method using the predicate and the table as the base query
var whereCall = Expression.Call(
typeof(Queryable),
"Where",
new[] { table.ElementType },
table.Expression,
predicate);
// Get an IQueryable<Region> which executes the where call on the table
var query = table.Provider.CreateQuery<Region>(whereCall);
var results = query.ToList();