查询 Linq to Sql Entity Framework c#
Query Linq to Sql Entity Framework c#
我在 SQL 中有此查询,但我不知道如何在 Linq 中执行此查询
这是查询
SELECT
GroupName, GroupsId
FROM
Groups
WHERE
GroupsId NOT IN (SELECT Groups.GroupsId
FROM AssignGroups
JOIN Groups ON AssignGroups.GroupsId = Groups.GroupsID
AND AssignGroups.UsersId = 1)
ORDER BY
GroupName
我正在使用 EF。
var result = from group in Groups
let validGroups = from aGroup in AssignGroups
from vGroup in Groups
where aGroup.GroupsId == vGroup.GroupsID &&
vGroup.UserId == 1
select vGroup.GroupsID
where validGroups.Contains(group.GroupID)
orderby group.GroupName
select group;
这里的关键是创建子查询的 "let" 子句,它是一个 IQueryable< T >,所以它可以与 "Contains" 子句一起使用(最终将被翻译成一个 "IN()" 条款)。
1) 您可以优化查询:
SELECT
g.GroupName
, g.GroupsId
FROM Groups g
LEFT JOIN AssignGroups ag
ON g.GroupsId = ag.GroupsId
AND ag.UsersId = 1
WHERE ag.GroupsId IS NULL
ORDER BY g.GroupName
2) 您的 linq 查询:
from g in context.Groups
join ag in context.AssignGroups
on new {g.GroupsId, UsersId = 1} equals new {ag.GroupsId, ag.UsersId} into ags
from ag in ags.DefaultIfEmpty()
where ag.GroupsId == null
orderby g.GroupName
select new {g.GroupName, g.GroupsId}
我在 SQL 中有此查询,但我不知道如何在 Linq 中执行此查询
这是查询
SELECT
GroupName, GroupsId
FROM
Groups
WHERE
GroupsId NOT IN (SELECT Groups.GroupsId
FROM AssignGroups
JOIN Groups ON AssignGroups.GroupsId = Groups.GroupsID
AND AssignGroups.UsersId = 1)
ORDER BY
GroupName
我正在使用 EF。
var result = from group in Groups
let validGroups = from aGroup in AssignGroups
from vGroup in Groups
where aGroup.GroupsId == vGroup.GroupsID &&
vGroup.UserId == 1
select vGroup.GroupsID
where validGroups.Contains(group.GroupID)
orderby group.GroupName
select group;
这里的关键是创建子查询的 "let" 子句,它是一个 IQueryable< T >,所以它可以与 "Contains" 子句一起使用(最终将被翻译成一个 "IN()" 条款)。
1) 您可以优化查询:
SELECT
g.GroupName
, g.GroupsId
FROM Groups g
LEFT JOIN AssignGroups ag
ON g.GroupsId = ag.GroupsId
AND ag.UsersId = 1
WHERE ag.GroupsId IS NULL
ORDER BY g.GroupName
2) 您的 linq 查询:
from g in context.Groups
join ag in context.AssignGroups
on new {g.GroupsId, UsersId = 1} equals new {ag.GroupsId, ag.UsersId} into ags
from ag in ags.DefaultIfEmpty()
where ag.GroupsId == null
orderby g.GroupName
select new {g.GroupName, g.GroupsId}