我的第一个开发角色已经 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;
Run Code Online (Sandbox Code Playgroud)
每个客户端可以有多个功能,每个功能都是一个单独的记录/行。
第一个查询应该返回特征为 8 但不是特征为 9 的所有客户端。但是,它会返回特征为 8 的所有客户端,无论客户端是否也具有特征 9。
第二个查询应该返回特征为 8 且特征为 9 的所有客户端。但是,它不会返回任何客户端。
有人可以告诉我我的查询有什么问题吗?
小智 5
您的 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;
Run Code Online (Sandbox Code Playgroud)
我不太确定你的主键列是什么。所以我只是猜测这是idY