这是我的SQL命令
SELECT KEY,NAME
from COMPANY c
WHERE KEY IN (select KEY from USER_COMPANY where UserId = @UserId)
order by NAME asc
所以我想将其转换为Entity Framework。
我试试这个
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);
但它不起作用。
如何在Entity Framework中使用SQL IN
关键字?
答案 0 :(得分: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;
答案 1 :(得分: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};
答案 2 :(得分:-1)
我的理解是,从.Contains()
到IN
的翻译只是被添加到EF6。
根据此工作项(http://entityframework.codeplex.com/workitem/245)和发行说明:改进了LINQ查询中Enumerable.Contains的性能。
所以在EF6中寻找它
答案 3 :(得分:-1)
您可以使用实体框架执行原始SQL查询。请看一下这个链接:http://msdn.microsoft.com/en-us/data/jj592907.aspx