Skip to content
Advertisement

Select items with the same foreign key

I have a question regarding Linq in C#.

Let’s say that I have 3 tables “Company”, “Employee” and “Job”.

Something like that: enter image description here

The important thing is that every work must be connected to a company but not necessarily to an employee. However, each employee must be connected to a company. For example we can have racord like that:

And now with linq I would like to get all jobs that are assigned to this employee and other employees from the same company. So in this case it will should are jobs with id 1 and 2 becouse employee 1 is assigned to company 1 and job with id 2 also has assigned to this company. How could I achieve this using linq but something like this: _context.Job.Where (x => x)

It is important to make only one query to the database.

Tkanks.

Advertisement

Answer

You can simplify the problem by thinking of it in two steps: find the company for a given employee, find all the jobs for that company:

In LINQ to SQL, EF Core 2.2 and EF Core 3.x the Any is translated to an EXISTS query in SQL.

Note since you know there should be only one answer to companyToFind, sending two queries to the database may be more efficient.

For LINQ to SQL or EF Core 3.x, you could also nest the first query and reduce to a single result:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement