Simple Example Subquery Linq

前端 未结 2 1106
旧巷少年郎
旧巷少年郎 2020-12-11 09:27

T-SQL Query

Select * from dbo.User_Users
Where UserID IN (Select UserID from Course_Enrollments)

LINQ to Entities alternative of Above Quer

相关标签:
2条回答
  • 2020-12-11 10:15
    from u in User_Users
    where u.Course_Enrollments.Any()
    select u
    

    if you have the foreign keys set up. If not you can do this

    from u in User_Users
    join cu in Course_Enrollments on u.UserId equals cu.UserId
    select u
    

    You also should wrap any of these with .Distinct() call

    0 讨论(0)
  • 2020-12-11 10:26

    Simple answer is use the "let" keyword and generate a sub-query that supports your conditional set for the main entity.

    var usersEnrolledInCourses = from u in User_Users
                                     let ces = from ce in Course_Enrollments
                                               select ce.UserID
                                     where ces.Contains(u.UserID)
                                 select u;   
    

    This will create an exists block in TSQL similar to

    SELECT [Extent1].*
       FROM dbo.User_Users AS Extent1
       WHERE EXISTS (SELECT 1 AS [C1]
                         FROM dbo.Course_Enrollements AS Extent2
                         WHERE (Extent2.UserID = Extent1.UserId))
    

    It's close to what you've asked for and will generally create the same query plan on SQL Server.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题