我在我的第一个开发角色中已经6个月了,并且已经开始在我们的存储库层中使用更多的LINQ来查询我们的数据库。对于我创建的两个查询,我真的需要一些帮助。
IQueryable<long> clientsWithoutFeature = from cf in db.Features
where cf.Feature != 9 && cf.Feature == 8
select cf.Client;
IQueryable<long> clientsWithFeature = from cf in db.Features
where cf.Feature == 9 && cf.Feature == 8
select cf.Client;每个客户端可以有多个功能,每个功能都是一个单独的记录/行。
第一个查询应该返回特征为8但不是特征9的所有客户端。但是,无论客户端是否也具有特征9,它都会返回特征为8的所有客户端。
第二个查询应该返回特征为8且特征为9的所有客户端。但是,它没有返回任何客户端。
有人能告诉我我的查询出了什么问题吗?
发布于 2016-12-07 13:59:13
您的sql正在执行您编写的sql。你需要稍微调整一下你的查询,以表达你的实际意图。
我倾向于使用这样的子查询方法:
IQueryable<long> clientsWithoutFeature = from cf in db.Features
where cf.Feature == 8 && !db.Features.Any(x => x.id == cf.id && x.Feature == 9)
select cf.Client;
IQueryable<long> clientsWithFeature = from cf in db.Features
where cf.Feature == 8 && db.Features.Any(x => x.id == cf.id && x.Feature == 9)
select cf.Client;我不太确定你的主键列是什么。所以我猜是idY
发布于 2016-12-07 14:09:41
这很简单。Features是一个表,其中单个行不能同时具有Feature value 8 和 9。
为了得到你想要的东西,你需要JOIN
IQueryable<long> clientsWithoutFeature = from cf1 in db.Features
join cf2 in db.Features on new { cf1.Client, IsTargetFeature = true }
equals new { cf2.Client, IsTargetFeature = cf2.Feature = 8 }
where cf1.Feature != 9
select cf1.Client;
IQueryable<long> clientsWithFeature = from cf1 in db.Features
join cf2 in db.Features on new { cf1.Client, IsTargetFeature = true }
equals new { cf2.Client, IsTargetFeature = cf2.Feature = 8 }
where cf1.Feature == 9
select cf1.Client;https://stackoverflow.com/questions/41010317
复制相似问题