3

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

So I want to convert it to Entity Framework.

I try like this

 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);

but it is not working.

How to use the SQL IN keyword in Entity Framework?

2
  • This isn't much help, but I'm on my phone and can't check code. You want to look into the LET keyword. Commented Aug 26, 2013 at 1:28
  • What does "not working" mean? Commented Aug 26, 2013 at 1:31

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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};

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.