2010-10-29 99 views
2

我使用動態表達式API(System.Linq.Dynamic)和LINQ to Entities。我的LINQ查詢如下。使用動態表達式API選擇匿名類型

var query = this.db.Products.AsQueryable() 
      .Where(strCondition) 
      .OrderBy("ProductNumber") 
      .Select("new(ProductNumber, ProductDescription, ProductCategory.Name)"); 

既然我有「查詢」,我不知道如何獲得每個字段的值。

string strTemp; 
foreach (var item in query) 
{ 
    strTemp = item.? 
} 

它是匿名類型,所以我不能真正使用強類型來獲取值。我能做什麼?我選擇獲取匿名類型字段的原因是因爲我需要將ProductCategory.Name字段放入結果中。使用Dynamic Expression API的結果中有沒有更好的方法來獲取ProductCategory.Name?誰能幫忙?

回答

0

只需使用您用來創建匿名對象的屬性名稱即可。 VS intellisense應該選擇它們。

string strTemp; 
     foreach (var item in query) 
     { 
      strTemp = item.ProductItem; 
     } 

您可以指定自己的屬性名稱,以及:

.Select("new(ProductNumber as Number, ProductDescription as Description, ProductCategory.Name as Name)") 
+0

問題是VS智能感知沒有拿起它。我假定它是因爲查詢使用的是使用字符串值的動態表達式API。任何線索? – Seecott 2010-10-29 17:22:05

+0

@Seecott - 你說得對。 VS不會接他們。看看這裏:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – 2010-10-29 20:24:08

+0

我看過在它之前。沒有答案。有誰知道如何或有一個示例代碼來獲取項目屬性? – Seecott 2010-10-29 20:39:10

1

對付它最簡單的方法來聲明循環變量是dynamic因爲你沒有任何靜態類型信息(推斷的靜態類型是object,但它是DynamicClass的實例)。

foreach (dynamic item in query) 
{ 
    string ProductNumber  = item.ProductNumber; 
    string ProductDescription = item.ProductDescription; 
    string Name    = item.Name; 
} 

否則,您可以手動使用反射。

// static (extension) method to read the property 
public static T GetProperty<T>(this DynamicClass self, string propertyName) 
{ 
    var type = self.GetType(); 
    var propInfo = type.GetProperty(propertyName); 
    return (T)propInfo.GetValue(self, null);   
} 

// usage: 
foreach (DynamicClass item in query) 
{ 
    // using as an extension method 
    string ProductNumber  = item.GetProperty<string>("ProductNumber"); 
    // or as a static method 
    string ProductDescription = GetProperty<string>(item, "ProductDescription"); 
    string Name    = item.GetProperty<string>("Name"); 
}