Azzedine Hassaini
Azzedine Hassaini

Reputation: 331

Entity Framework, select many to many

I am working with Entity Framework code first.

I have the following tables :

Companies : PK ID int, Name, ...
Customers : PK ID int, Name, ...
CustomersCompanies : CustomerID, CompanyID

I can create customers and companies without problems. But I don't know how to get all the companies a customer has.

I tried that :

_customer = ...
var companies = from c in _db.Companies
                        where c.Customers.Contains(_customer)
                        select c;

But companies does not contains anything...

Upvotes: 0

Views: 1384

Answers (3)

tomalone
tomalone

Reputation: 404

Try to compare by ID's of customers, like:

_customer = ...
var companies = from c in _db.Companies
                    where c.Customers.Where(x => x.CustomerID == c.CompanyID)
                    select c;

Or shorter:

var comapnies = _db.Companies.Select(x => x.CustomerID == c.CompanyID);

Upvotes: 1

officert
officert

Reputation: 1232

If you are using code first you can just add a virtual collection of Companies to your Customer class, and a virtual collection of Customers to your Company class :

public class Customer 
{ 
    public int Id { get; set; }

    public virtual ICollection<Company> Companies { get; set; }
}

public class Company
{
    public int Id { get; set; }

    public virtual ICollection<Customer> Customers { get; set; }
}

then to fetch customers and include their companies you can do :

var customers = _db.Customers.Include(x => x.Companies);

I'm not sure what your _db class looks like so I don't know if you just have your entity collections as properties on it. Typically I use the entity framework DbContext which has a GetDbSet method. So I would do something like :

var customers = _dbContext.GetDbSet<Customer>().Include(x => x.Companies);

Hope that helps!

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

With properly created Entities you should be able to just call:

var companies = _customer.Companies;

you have to have ICollection<Company> within your Customer class, and ICollection<Customer> within Company class.

Check out this tutorial: Creating a Many To Many Mapping Using Code First.

Upvotes: 0

Related Questions