pistacchio
pistacchio

Reputation: 58863

Entity Framework Associations

I've created a Model with Entity Framework from three database tables:

  1. Agents
  2. AgentsGroups
  3. Groups

AgentsGroups is a simple table with three columns: 1 id and two foreign keys linking Agents and Groups (every Agent can have multiple Groups). Pretty basic stuff.

Entity Framework correctly recognizes the relationships between the table. Now, with LINQPad I am able to get the names of all the groups associated with an agent starting from the agent ID:

from a in Agents
    join ag in AgentsGroups on a.Code equals ag.AgentCode
    join g in Groups on ag.GroupCode equals g.Code
    where a.Code == 10199
    select g.Name

This, though, doesn't work on the very program as, in fact, AgentCode and GroupCode are mapped as Associations, not fields.

I guess I have to use Include, but I've never used it, so the help requested is: how could I translate the given semi-working linq expression in a similar expression giving out the Group Names but using Associations?

Thanks in advance

Upvotes: 1

Views: 497

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

Much simpler in EF:

from a in Agents
where a.Code == 10199
from g in a.Groups
select g.Name

You almost never use join in EF.

Upvotes: 2

Related Questions