How to use 'In' SQL keyword in Entity Framework?

后端 未结 3 389
失恋的感觉
失恋的感觉 2021-01-20 18:52

This is my SQL command

SELECT KEY,NAME
from  COMPANY c 
WHERE     KEY IN (select KEY from USER_COMPANY  where UserId = @UserId)
order by NAME asc
         


        
3条回答
  •  青春惊慌失措
    2021-01-20 19:24

    Note that this SQL query has the exact same meaning:

    SELECT c.KEY, c.NAME
    FROM COMPANY c
    JOIN (SELECT DISTINCT KEY FROM USER_COMPANY where UserId = @UserId) u
    ON U.KEY = C.KEY
    ORDER BY c.NAME asc
    

    So you should be able to just do:

    var userCompany = (from u in db.USER_COMPANY
                       where u.UserId == UserId 
                       select(u.KEY)).Distinct();
    
    var result = from c in db.COMPANY
                 join u in userCompany
                 on c.KEY = u.KEY
                 select new {c.KEY, c.NAME};
    

提交回复
热议问题