Question

I have got two entity POCO entities with many to many relationships, e.g.

public class Employee
{
    public int Id;
    public string Name;
    public virtual ICollection<Organization> Organizations {get;set;}
}

public class Organization
{
    public int Id;
    public string Name;
    public virtual ICollection<Employee> Employees {get;set;}
}

I want to fetch Employee.Name, Employee.Id, OrganizationID using LINQ. It would repeat data for Employee, but I am ok with it. How should I write LINQ to EF for this.

Was it helpful?

Solution

var query = from e in context.Employee
            from o in e.Organizations
            select new
            {
              EmployeeName = e.Name,
              EmployeeId = e.Id,
              OrganizationId = o.Id
            }

OTHER TIPS

As per above structure, you should have foreign key in one of the table. So no need to take both the entity objects, just take one in which the foreign key of other is available and you will get the Icollection object of other entity.

if Employee is having foreign key for Organisation then you can do something like:

var objEmp = context.Employee;

so you will get whole Employee entity in objEmp and wherever you want to use Organisation entity, you will get Icollection of Organisation as you are having many to many relationship in following way:

var objOrg = objEmp.Organisations;

you can use FirstOrDefault() or SingleOrDefault() method to retrieve first or one record in above query with lambda expression.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top