首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WHERE子句中具有多个条件的LINQ查询

WHERE子句中具有多个条件的LINQ查询
EN

Stack Overflow用户
提问于 2016-12-07 13:51:41
回答 2查看 15.6K关注 0票数 1

我在我的第一个开发角色中已经6个月了,并且已经开始在我们的存储库层中使用更多的LINQ来查询我们的数据库。对于我创建的两个查询,我真的需要一些帮助。

代码语言:javascript
复制
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的所有客户端。但是,它没有返回任何客户端。

有人能告诉我我的查询出了什么问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-07 13:59:13

您的sql正在执行您编写的sql。你需要稍微调整一下你的查询,以表达你的实际意图。

我倾向于使用这样的子查询方法:

代码语言:javascript
复制
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

票数 4
EN

Stack Overflow用户

发布于 2016-12-07 14:09:41

这很简单。Features是一个表,其中单个行不能同时具有Feature value 8 9

为了得到你想要的东西,你需要JOIN

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41010317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档