2011-05-11 57 views
3

是否可能將IQueryable對象轉換爲IQueryable,其中T是映射實體? (T將是一個POCO課程)。IQueryable to IQueryable <T>

在此先感謝。

+2

而你如何獲得非泛型'IQueryable'? – 2011-05-11 13:08:16

回答

8

只是Cast<T>()而已。假設它是一個相同類型的查詢。否則,您可以使用OfType<T>()過濾方法來過濾某種類型的項目。

IQueryable query = ...; 
IQueryable<MyType> x = query.Cast<MyType>(); // assuming the queryable is of `MyType` objects 
IQueryable<MyDerivedType> y = query.OfType<MyDerivedType>(); // filter out objects derived from `MyType` (`MyDerivedType`) 

不過你的情況,你說你正在使用動態LINQ和做一個動態的投影。考慮這個完全由查詢:

var query = dc.SomeTable 
       .Where("SomeProperty = \"foo\"") 
       .Select("new (SomeProperty, AnotherProperty)"); 

它導致IQueryable類型的查詢。你不能把這個投射到一個特定類型的查詢IQueryable<T>畢竟什麼是T? Dynamic LINQ庫所做的是創建一個從DynamicCass派生的類型。你可以投到IQueryable<DynamicClass>query.Cast<DynamicClass>()),但你將無法訪問屬性,所以它是沒有意義的。

真的,你擁有的唯一不錯的選擇是在這種情況下使用dynamic來訪問這些屬性。

foreach (dynamic x in query) 
{ 
    string someProperty = x.SomeProperty; 
    int anotherProperty = x.AnotherProperty; 
    // etc... 
} 

如果你想將其轉換爲您的POCO對象的查詢,你必須做轉換爲一個單獨的步驟,但使用LINQ to對象。

IEnumerable<SomePoco> query = 
    dc.SomeTable 
     .Where("SomeProperty = \"foo\"") 
     .Select("new (SomeProperty, AnotherProperty)") 
     .Cast<DynamicObject>().AsEnumerable().Cast<dynamic>() 
     .Select(x => new SomePoco 
     { 
      SomeProperty = x.SomeProperty, 
      AnotherProperty = x.AnotherProperty, 
     }); 

如果您必須有IQueryable<T>,那麼您不應該首先使用動態投影。

IQueryable<SomePoco> query = 
    dc.SomeTable 
     .Where("SomeProperty = \"foo\"") 
     .Select(x => new SomePoco 
     { 
      SomeProperty = x.SomeProperty, 
      AnotherProperty = x.AnotherProperty, 
     }); 

看到如何投不工作的LINQ到實體,那麼我想你必須讓你的POCO對象的強類型集合唯一的選擇是打破了這一點,進入一個循環。

var query = dc.SomeTable 
       .Where("SomeProperty = \"foo\"") 
       .Select("new (SomeProperty, AnotherProperty)"); 

var result = new List<SomePoco>(); 
foreach (dynamic x in query) 
{ 
    result.Add(new SomePoco 
    { 
     SomeProperty = x.SomeProperty, 
     AnotherProperty = x.AnotherProperty, 
    }); 
} 
+0

我得到System.Exception:不能執行類型轉換.. Linq轉換爲實體只支持對原始類型轉換.. – Alex70 2011-05-11 13:28:00

+0

所有我需要的是實現一個IQueryable 從動態linq到實體: 步驟1:我已經像這樣 - > var query1 = myCtx.Where(.. lambda); 第2步:我必須選擇只是一些領域(我不能在這裏使用拉姆達),所以: VAR QUERY2 = query1.Select(「myFiled1,myFiled2); 第2步是可以實現的,通過ScottGu的System.Linq.Dynamic.dll 。圖書館 問題就在這裏:在步驟2中返回一個IQueryable,而我需要的IQueryable 其中T是我的POCO類 我不能convert..I轉換過程中始終得到異常.. – Alex70 2011-05-11 14:19:20

+0

@Alex:這是如果信息在您提問時很有用,那麼在這種情況下,由於您投射到動態類型和技術上,您不能投射到特定類型,因此您不知道編譯時間類型。然而,你可以強制轉換爲DynamicClass,因爲這是對象派生的類型,除非你使用'dynamic'變量,否則你將無法直接訪問這些字段。 – 2011-05-11 21:01:22