2012-04-13 60 views
5

我有以下形式的LINQ實體查詢:不支持嵌套查詢。 Operation1 =「UnionAll」操作2 =「MultiStreamNest」

var x = from a in SomeData 
    where ... some conditions ... 
    select new MyType 
    { 
     Property = a.Property, 
     ChildCollection = from b in a.Children 
         select new MyChildType 
         { 
          SomeProperty = b.Property, 
          AnotherProperty = b.AnotherProperty 
         } 
    }; 

var y = from a in SomeData 
    where ... some other conditions ... 
    select new MyType 
    { 
     Property = a.Property, 
     ChildCollection = from b in a.Children 
         select new MyChildType 
         { 
          SomeProperty = b.Property, 
          AnotherProperty = b.AnotherProperty 
         } 
    }; 

var results = x.Concat(y); 

(這是一個簡化的例子 - 的「其中」和「選擇」子句是更復雜。比這裏顯示我使用單獨的查詢語句創建一個組合一個太複雜,有太多的條件語句,並採取一個時代編譯)

編譯罰款,但所不同的執行失敗:

"The nested query is not supported. Operation1='UnionAll' Operation2='MultiStreamNest' 

請注意,我試圖投影到嵌套的類型結構。如果我在Concat()之前的x和y上調用.ToList(),那麼它工作正常。還有一點,我的一個屬性是一個枚舉,但我使用整數包裝屬性來分配它。

有沒有一種方法可以做我想做的事情,而無需將所有數據存入內存?或者它是導致失敗的枚舉?

感謝,

牛逼

回答

0

你有沒有試着用

var results = x.Union(y); 

TIZ

var x = (from a in SomeData 
where ... some conditions ... 
select new MyType 
{ 
    Property = a.Property, 
    ChildCollection = (from b in a.Children 
        select new MyChildType 
        { 
         SomeProperty = b.Property, 
         AnotherProperty = b.AnotherProperty 
        }).ToArray() //or DefaultIfEmpty 
}).Concat(
from a in SomeData 
where ... some other conditions ... 
select new MyType 
{ 
    Property = a.Property, 
    ChildCollection = (from b in a.Children 
        select new MyChildType 
        { 
         SomeProperty = b.Property, 
         AnotherProperty = b.AnotherProperty 
        }).ToArray() //or DefaultIfEmpty 
}); 
+0

剛剛嘗試過其中的第二個,看起來和第一個完全一樣,即沒有按照我的希望工作(請參閱我對@ Arion的帖子的評論。 – 2012-04-13 09:59:50

+0

...現在已被刪除。不管怎樣,不介意使用Union作爲結果集應該是不同的,但我會得到異常「The Distinct'操作不能應用於指定參數的集合ResultType」,我相信這是因爲Distinct無法處理嵌套 – 2012-04-13 10:12:12

+0

如果爲空?它的行爲如何? – innovia 2012-04-13 12:32:15

0

我有類似的問題,而試圖串聯或聯合多套導航性能爲單一的IEnumerable,這裏是代碼示例:

var requiredDocuments =     
       (from x in db.RequestTypes where (some condition) select x.RequiredDocuments) 
       .SelectMany(r => r).ToList<DataModel.RequiredDocument>() 
       .Concat(
       (from c in db.Categories where (some condition) select c.RequiredDocuments) 
       .SelectMany(r => r).ToList<DataModel.RequiredDocument>() 
       ) 
       .Concat(
       (from f in db.Fields where (some condition) select f.RequiredDocuments) 
       .SelectMany(r => r).ToList<DataModel.RequiredDocument>() 
       ); 
+0

這是您有問題的代碼位或工作位? – Jerther 2016-06-14 13:00:38

+0

因爲在執行Concat之前調用了ToList,所以這應該起作用。 – Florian 2016-06-21 09:31:52

0

如果我正確理解你正在嘗試做什麼,我已經多次遇到同樣的問題。底線是,不支持使用嵌套投影的工會,如果您需要這樣做,您必須首先使用ToList實現結果。