3

这是我的 SQL 命令

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

所以我想将它转换为实体框架。

我试试这样

 var userCompany = (from u in db.USER_COMPANY
                         where u.UserId == UserId 
                         select(u.KEY));

            var user = (from c in db.COMPANY
                        where (c => userCompany.Contains(c.KEY)
                        select c);

但它不工作。

如何IN在实体框架中使用 SQL 关键字?

4

3 回答 3

4

尝试这个:

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;
于 2013-08-26T01:29:23.070 回答
1

请注意,此 SQL 查询具有完全相同的含义:

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

所以你应该能够做到:

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};
于 2013-08-26T01:30:22.990 回答
-1

我的理解是,从.Contains()to的翻译IN只是被添加到 EF6 中。

根据此工作项 ( http://entityframework.codeplex.com/workitem/245 ) 和发行说明:改进了 LINQ 查询中 Enumerable.Contains 的性能。

所以在EF6中寻找

于 2013-08-26T01:17:41.733 回答