Michel
Michel

Reputation: 23615

Linq to entities outer join, then an inner join

i have this code:

var query = (from p in dc.GetTable<Person>()
join pa in dc.GetTable<PersonAddress>() on p.Id equals pa.PersonId into tempAddresses
from addresses in tempAddresses.DefaultIfEmpty()
select new { p.FirstName, p.LastName, addresses.State });

this works good, as a outer join for persons with their (optional) address.

Now i want to join addresstype to this query with an inner join, because every address has exactly one addresstype. So for every person, get the address, and if it has an address, also get the addresstype.

So i created this (added the inner join to addresstype):

var query = (from p in dc.GetTable<Person>()
join pa in dc.GetTable<PersonAddress>() on p.Id equals pa.PersonId into tempAddresses
from addresses in tempAddresses.DefaultIfEmpty()
join at in dc.GetTable<AddressTypes>() on pa.addresstypeid equals at.addresstypeid
select new { p.FirstName, p.LastName, addresses.State, at.addresstype }); 

Now i get an null reference error on the pa.addresstypeid when the person has no address....

Is there a way to create this in linq?

The above code is behavioural exactly like my code, but my code has different entities but i'm not allowed to show actual code...

EDIT:

here is an example from my code which actually works: (replace the tables with foo/bar)

from foo in foos
join bar in new barRepository(SessionTicket).GetList()
    on foo.barId equals bar.barId
join barpersonbar in new barPersonbarRepository(SessionTicket,personId).GetList().Where(z=>z.PersonId == personid)
    on bar.barId equals barpersonbar.barId
    into outerbarpersonbar
from barpersonbar in outerbarpersonbar.DefaultIfEmpty()

Isn't that the same as in your comment, that 'pa' is out of scope, isn't that the 'bar' in this code

Upvotes: 2

Views: 166

Answers (1)

Aducci
Aducci

Reputation: 26644

pa isnt in scope once you use the into

change

on pa.addresstypeid equals

to

on addresses.addresstypeid equals

Upvotes: 2

Related Questions