2012-02-11 44 views
1

我汲取靈感的一部分:表達式樹從這個問題的一個屬性

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

回答

1

您將定義AwesomeProperty就像您的LINQ to SQL對象上的任何其他屬性。假設它的類型爲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();