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

后端 未结 3 359
失恋的感觉
失恋的感觉 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:06

    My understanding is that the translation from .Contains() to IN is only just being added to EF6.

    According to this work item (http://entityframework.codeplex.com/workitem/245) and the release note: Improved performance of Enumerable.Contains in LINQ queries.

    So look for it in EF6

    0 讨论(0)
  • 2021-01-20 19:07

    Try this:

    var query = from c in db.COMPANY
                where (from u in db.USER_COMPANY
                       where u.UserId == UserId
                       select u.KEY).Contains(c.KEY)
                orderby c.NAME
                select c.KEY, c.NAME;
    
    0 讨论(0)
  • 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};
    
    0 讨论(0)
提交回复
热议问题