除Contains()运算符外,本地序列不能用于查询运算符的LINQ to SQL实现
我在我的项目中使用LINQ,我的代码是:
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;
遇到此错误dataGridView1.DataSource = SE;
错误信息是:
除Contains()运算符外,本地序列不能用于查询运算符的LINQ to SQL实现。
您不能在SQL源和本地源之间使用Join。 您需要先将SQL数据放入内存,然后才能加入它们。 在这种情况下,你实际上并没有进行连接,因为你只从第一个集合中获取元素,你想要的是一个select … where … selectid in query,你可以使用Contains方法获得。
var SE = Shop.Sections.Where( s => obj.SectionObjects .Select( so => so.SectionId ) .Contains( s.SectionId )) .ToList();
转换为
select * from Sections where sectionId in (...)
其中in子句的值来自本地对象集合中的id列表。
您不能将本地源加入SQL源,但您可以将SQL源加入本地,vv
var SE = from c1 in obj.SectionObjects join c in Shop.Sections on c1.SectionId equals c.SectionId select c;
换句话说,本地资源必须首先出现
这应该可以在数据库端(使用IN
)而不是在内存中完成:
var SE = from c in Shop.Sections where obj.SectionObjects.Select(z => z.SectionId).Contains(c.SectionId) select c;
L2S Profiler对这些事情非常有帮助 – 您可以比较我的解决方案和其他解决方案生成的不同SQL。
var SE =来自Shop.Sections.AsEnumerable()中的c。ToList()在obj.SectionObjects.AsEnumerable()中连接c1。c.SectionId上的ToList()等于c1.SectionId select c;
dataGridView1.DataSource = SE;