1

I have problem retrieving data in many to many relationship using linq.

I have 3 tables

  • Employee
  • role
  • RoleInemployee

The third table has two columns: empid and roleid

An employee can assigned to multiple roles are stored in third table or you can say single role assigned to multiple employee.

I just want to retrieve employee who have particular role id using linq.

I'm using navigation property in employee model like

public virtual ICollection<Role> role {get;set;} 

This navigation property give me role for particular employee but I want to retrieve employees data which is having a particular role is assigned.

Can any body help?

1
  • see edited answer... for edited question. Commented Jan 23, 2013 at 23:03

2 Answers 2

2

Count has an overload with a predicate as parameter, so you can do

   var count =  db.Employees.Count(emp=> emp.role.Any(r=> r.Id == 12));

Edit

to get employees with a particular role

var employees = db.Employees.Where(emp => emp.role.Any(r => r.Id == 12));
Sign up to request clarification or add additional context in comments.

Comments

1

If I understood the question correctly you want to get the number of employees set to a particular role id using LINQ.

If your entity framework Employee class has a list of roles included -- you can do the following with your list of employees where 123 is the RoleID you are looking for:

employeeList.Where(x => x.Roles.Where(y => y.RoleID == 123)).Count();

EDIT: Removed RoleInEmployee code

2 Comments

For second solution : in EF, RoleInEmployee class probably doesn't exist (this is an object world, not a db one, and it's not needed in object).
yes RoleInEmployee class does not exist.can we load data on employee object for particular role.can you tell me how to made linq query for that

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.