0

我正在尝试运行类似于

var results = MyItem.MyEntitySet.Where( x => x.PropertyB == 0 )

MyEntitySet 与 MyItem 有一个关联,PropertyA。

理想情况下,底层 SQL 查询应该是

SELECT .. FROM .. WHERE ([t0].[PropertyA] = @p0) AND ([t0].[PropertyB ] = @p1)

因为 PropertyA 和 PropertyB 是我正在查询的表的两个主键。

但我的痕迹似乎表明该程序首先使用 PropertyA 查询返回MyEntitySet,然后使用 PropertyB 查询返回var results

无论如何我可以强制 Linq 在单个 SQL 语句中查询这两个条件吗?

4

1 回答 1

0

Maybe, maybe not. The generated SQL does match the way you're writing the LINQ query, so the generated SQL isn't a surprise. If you started with the entity represented by "MyEntitySet" then, maybe, the generated SQL would change.

It's not immediately clear whether you're using LINQ to SQL or Entity Framework. LINQ to SQL does represent one-to-many relationships as an "entity set", while Entity Framework treats relationships as first-class objects, so that a one-to-many relationship is a set of relationship objects with related entities, rather than simply an entity set. It does affect the generated SQL.

Two other thoughts...

If you want that much control over the generated SQL, you probably won't be happy with LINQ. It doesn't always generate optimal SQL (although it can sometimes surprise you). On the other hand, one of the major benefits of LINQ is that you start writing code that expresses the real relationships in your data. The downfall of classic ADO.NET is that you write code about manipulating SQL and processing DataSet and DataTable collections. LINQ is infinitely cleaner, safer, more robust, and more maintainable code to write. Everything is a trade-off.

Second, the query generation is likely to get better over time (especially in Entity Framework).

于 2009-10-14T20:56:19.290 回答