带有“不在”的实体框架查询
Posted
技术标签:
【中文标题】带有“不在”的实体框架查询【英文标题】:Entity Framework query with "not in" 【发布时间】:2014-01-01 16:20:11 【问题描述】:我对相关表有一个简单(非常简单,不简单)的“不在”查询。
SELECT CompetencyID, CompetencyName FROM Competency
WHERE (Deleted = 0) AND (CompanyID = 1) AND (CompetencyID NOT IN(SELECT CompetencyID
FROM CompetencyGroups WHERE (Deleted = 0) AND (CompanyID = 1) AND (GroupID = 1))) AND
(ParentID = 0) ORDER BY CompetencyName
在 SQL 中,我得到了我需要的列表,其中包含不在组中的剩余项目。现在我想使用 EF5 将它绑定到 DataGrid。
我无法正确获取查询语法(使用 VB.net)来列出能力的 ID 和名称...
将提供的 c# 答案转换为 VB:
Dim excludeList = context.CompetencyGroups.Where(Function(x) x.Deleted = False And x.GroupID = GroupID).Select(Function(x) x.CompetencyID).ToArray
Dim results = context.Competencies.Where(Function(c) Not excludeList.Contains(c.CompetencyID) And c.Deleted = False And c.CompanyID = 1 And c.ParentID = 0).OrderBy(Function(c) c.CompetencyName)
GridView2.DataSource = results
GridView2.DataBind()
希望这对将来的某人有所帮助。我花了大约 4 个小时来搜索、询问和转换...
【问题讨论】:
【参考方案1】:类似
var excludeList = context.CompetencyGroups.Where(x => x....).Select(x => x.CompetencyID).ToArray();
var results = context.Competency.Where(x => !excludeList.Contains(x.CompetencyID));
更新:其他人对此进行了编辑,然后有人拒绝了它,但编辑很好(选择值)
【讨论】:
有人可以将其转换为 VB 吗?我试图实现,但可惜我迷失在Where(x => x....).Select(x => x.CompetencyID
【参考方案2】:
如果你需要 Cast 来制作一个整数数组。
Dim excludeList = context.CompetencyGroups.Cast(Of CompentencyGroup).Select(Function(x) x.CompetencyID).ToArray()
Dim results = context.Competency.Where(Function(x) Not excludeList.Contains(x.CompetencyID))
【讨论】:
以上是关于带有“不在”的实体框架查询的主要内容,如果未能解决你的问题,请参考以下文章