mohaidar
mohaidar

Reputation: 4286

how to apply inner join in entityframework LINQ method syntax?

How to apply this query in entity framework method syntax

select company_id, country_id from companies, departments where companies.company_id == departments.company_id and department.departmentId = 10;

So far, I have:

var company = context.companies
    .Where(com => com.Departments
        .Contains(context.departments
            .Where(dep => dep.department_id==_user.Department)
            .FirstOrDefault()
        )
    )
    .Select(com => new { com.company_id, com.Country })
    .FirstOrDefault();

Upvotes: 0

Views: 475

Answers (1)

Inspector Squirrel
Inspector Squirrel

Reputation: 2548

Using method based syntax, this could be as simple as;

var company = context.Companies
    .Where(x => x.Departments
        .Any(x => x.department_id == _user.Department)
    )
    .Select(x => new { x.company_id, x.Country });

This assumes your tables are set up with foreign keys giving each Company a list of Department objects. It very much depends on your data structure.

Upvotes: 2

Related Questions