如何使用Entity Framework在子查询中执行操作?

时间:2017-10-12 19:22:03

标签: c# entity-framework

我有一个类似的查询:

var result = from u in this.DataContext.Users
             join l in DataContext.Locations on u.Id equals l.userId
             where u.active == 1
             select u;

return result ;

我想添加一个子查询WHERE IN子句,如:

WHERE u.Id IN (SELECT userId FROM approved_users)

这可能吗?

1 个答案:

答案 0 :(得分:1)

我不确定为什么要在子查询中使用它,只是加入Approved Users表似乎更简单,但我不知道要求所以我提出了两个选项。一个选项,具有子查询和一个带有附加连接的选项。我也假设您没有任何导航属性。

选项1 - 子查询:

var subQuery =
    from u in context.Users.Where(x => context.ApprovedUsers.Select(y => y.ApprovedUserId).Contains(x.UserId))
    join l in context.Locations on u.UserId equals l.UserId
    where u.IsActive == true
    select u;

生成类似这样的东西

SELECT 
    [Extent1].[UserId] AS [UserId], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[IsActive] AS [IsActive]
FROM  [dbo].[User] AS [Extent1]
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[UserId] = [Extent2].[UserId]
WHERE ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[ApprovedUser] AS [Extent3]
    WHERE [Extent3].[ApprovedUserId] = [Extent1].[UserId]
)) AND (1 = [Extent1].[IsActive])

选项2 - 其他加入:

var query =
    from u in context.Users
    join l in context.Locations on u.UserId equals l.UserId
    join au in context.ApprovedUsers on u.UserId equals au.ApprovedUserId
    where u.IsActive == true
    select u;

生成:

SELECT 
    [Extent1].[UserId] AS [UserId], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[IsActive] AS [IsActive]
FROM   [dbo].[User] AS [Extent1]
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[UserId] = [Extent2].[UserId]
INNER JOIN [dbo].[ApprovedUser] AS [Extent3] ON [Extent1].[UserId] = [Extent3].[ApprovedUserId]
WHERE 1 = [Extent1].[IsActive]