Tom
Tom

Reputation: 4087

Linq query from navigation properties

In entity framework i have two table (two entities): People and Role with one to many relationship. In the People tables i have a navigation property to Role:

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

I'm able to retrieve all people that have role as 'barman':

var listPeople = (from p in SiContext.People
                  where p.Roles.Any(x => x.Name == "barman")
                  select p).ToList();

How can i retrieve all people with the related role? I want the person name and surname and the role name (that is in the role table)

Thanks

Upvotes: 0

Views: 282

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109109

You can select from multiple entities:

from p in SiContext.People
from r in p.Roles
select new { Name = p.Name, ..., Role = r.Name }

Upvotes: 0

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

This?

var peoples = SiContext.People.Include("Roles");

or

var peoples = SiContext.People.Include(p => p.Roles);

Upvotes: 2

Related Questions