LINQ&多对多关系
所以我正在编写一个“动态”Linq 查询。我创建了一个“选项”类,其中包含可以作为查询一部分的所有动态选项。其中一些选项属性是 List 对象,它们保存我想要返回的实体的 ID,这些实体是 SQL Server 中多对多关系的一部分。快速代码示例和表格描述可能会有所帮助(为了简洁起见,认真精简)。
桌车: ID int PK, 型号 varchar(50), 年份 int
表格颜色: ID int PK, 名称 varchar(50)
Table CarsXColors: CarId int PK, ColorId int PK
public IEnumerable<Car> Search(SearchOptions options)
{
var query = from car in ctx.Cars select car;
// This works just fine
if (options.MaxMileage.HasValue) query = query.Where(x => x.Mileage <= options.Mileage.Value);
// How do I implement this pseudo code. options.Colors is a List<int>
if (options.Colors.Count > 0)
{
query = query.Where( -- select cars that are in the List<int> of colors --);
}
return query;
}
So I'm writing a "dynamic" Linq query. I've created an "options" class that holds all of the dynamic options that can be a part of the query. Some of these option properties are List objects, which hold IDs of entities that I want to return that are part of many-to-many relationships in SQL Server. A quick code example and descriptions of the tables might help (seriously pared down for brevity).
Table Cars:
Id int PK,
Model varchar(50),
Year int
Table Colors:
Id int PK,
Name varchar(50)
Table CarsXColors:
CarId int PK,
ColorId int PK
public IEnumerable<Car> Search(SearchOptions options)
{
var query = from car in ctx.Cars select car;
// This works just fine
if (options.MaxMileage.HasValue) query = query.Where(x => x.Mileage <= options.Mileage.Value);
// How do I implement this pseudo code. options.Colors is a List<int>
if (options.Colors.Count > 0)
{
query = query.Where( -- select cars that are in the List<int> of colors --);
}
return query;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我看到您已经得到了答案,但也要考虑这种替代方案:
这种风格很常见,因为它始终生成相同的 SQL 语句,以便数据库引擎或 LINQ 实际上可以缓存查询和/或查询计划以实现更快的响应。
如果 options.Colors 为空,数据库查询优化器将自动消除 WHERE 子句,因此您无需为此付出任何性能损失。
I see that you already got the answer, but also consider this alternative:
This style is quite common as it generates the same SQL statement throughout so that database engines or LINQ can actually cache the query and/or query plan for faster response.
The database query optimizer will automatically eliminate the WHERE clause if options.Colors is empty, so you are not paying any performance penalties here.
回答了我自己的问题...
Answered my own question...