2011-08-03 34 views
1

我对LINQ很新,所以我假设我错过了一些简单的东西。我有一个生成下面的错误代码:局部序列不能在LINQ中使用到SQL简单的LINQ问题:“本地序列无法使用”错误

return (from x in db.CurrentTrackings 
       where x.strLocation == BarCode || 
       (from b in ChildBranches where x.strLocation == b.BarCode select b).Count() > 0 || 
       (from c in PlantCustomers where x.strLocation == c.customer_str_id select c).Count() > 0 
       select x).Count(); 

请让我知道,如果你需要进一步澄清。这似乎应该工作,但我必须错过一些东西。

回答

2

你不能有本地序列(例如,ChildBranches)与LINQ到SQL查询混合(即db.CurrentTrackings),因为LINQ到SQL供应商不支持的子查询任何翻译本地查询到SQL查询。 LINQ到SQL 确实支持载有()本地序列,在这种情况下,将其转换为WHERE X IN (Y1, Y2, Yn)声明:

var barCodes = ChildBranches.Select(b=>b.BarCode); 
var customerIds = PlantCustomers.Select(c=>c.customer_str_id); 

return (from x in db.CurrentTrackings 
     where x.strLocation == BarCode || 
       barCodes.Contains(x.strLocation) || 
       customerIds.Contains(x.strLocation) 
     select x).Count(); 
+0

这很好用!现在我的麻烦是,我有这么多的数据,而且我不得不多次调用这个查询,所以它真的很慢。 – zmarks22

+0

看看使用编译查询? –

0

该查询生成将发送到SQL Server的SQL语句,但ChildBranches和PlantCustomers集合无法传递到SQL Server。

1

LocalSequences不能转换为SQL除非你使用包含了那么您的查询可能想

return (from x in db.CurrentTrackings 
     where 
     x.strLocation == BarCode || 
     ChildBranches.Select(b=>b.BarCode).Contains(x.strLocation) || 
     PlantCustomers.Select(c=>c.customer_str_id).Contains(x.strLocation) 
     select x).Count();