2012-04-13 72 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实现结果。