本地序列不能在 LINQ to SQL 的查询运算符实现中使用,除了 Contains() 运算符

本地序列不能在 LINQ to SQL 的查询运算符实现中使用,除了 Contains() 运算符

问题描述:

我在我的项目中使用 LINQ,我的代码是:

I am using LINQ in my project and my code is:

var SE = from c in Shop.Sections
                    join c1 in obj.SectionObjects on c.SectionId equals c1.SectionId
                    select c;

 dataGridView1.DataSource = SE;

但是我在 dataGridView1.DataSource = SE;
行中遇到了这个错误错误信息是:

but I face this error in line dataGridView1.DataSource = SE;
error message is:

本地序列不能在 LINQ to SQL 的查询运算符实现中使用,除了 Contains() 运算符.

Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.

不能在 SQL 源和本地源之间使用联接.您需要先将 SQL 数据放入内存中,然后才能加入它们.在这种情况下,您并没有真正进行连接,因为您只从第一个集合中获取元素,您想要的是 select...where...selectid in 查询,您可以使用Contains方法获取.

You can't use a Join between a SQL source and a local source. You'll need to bring the SQL data into memory before you can join them. In this case, you're not really doing a join since you only take the elements from the first collection, what you want is a select...where...selectid in query, which you can get using the Contains method.

 var SE = Shop.Sections.Where( s => obj.SectionObjects
                                       .Select( so => so.SectionId )
                                       .Contains( s.SectionId ))
                       .ToList();

翻译成

select * from Sections where sectionId in (...)

其中 in 子句的值来自本地对象集合中的 id 列表.

where the values for the in clause come from the list of ids in the collection of local objects.