简单的LINQ问题:“不能使用局部序列”错误

本文关键字:用局 错误 不能 LINQ 问题 简单 | 更新日期: 2023-09-27 18:04:29

我对LINQ很陌生,所以我假设我错过了一些简单的东西。我有生成以下错误的代码:本地序列不能在LINQ to SQL中使用

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();

如果你需要更多的说明,请告诉我。这似乎应该工作,但我一定是错过了什么

简单的LINQ问题:“不能使用局部序列”错误

您不能将本地序列的子查询(例如,ChildBranches)与LINQ-to-SQL查询(例如,db.CurrentTrackings)混合在一起,因为LINQ-to-SQL提供程序不支持将本地查询转换为SQL查询。LINQ to SQL 对本地序列支持Contains(),在这种情况下,它将其转换为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();

LocalSequences不能被翻译成SQL,除非当你使用Contains所以你的查询可能要

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();

查询生成一个SQL语句,该SQL语句将被发送到SQL Server,但是ChildBranches和PlantCustomers集合不能被传递到SQL Server。