user1237131
user1237131

Reputation: 1863

how to join muliple tables at a time using linq to sql?

Users:

userid    name     email
  1       venkat   [email protected]
  2       venu     [email protected]
  3       raghu    [email protected]

Partners:

    id   userid   partnerid  status
    1     1        2           1
    2     1        3           1

location:

    id   userid    lat    lon
    1     1        12.00  13.00
    2     2        14.00  12.00
    3     3        14.00  14.23

Query:

var result = from partner in Partners
                join user in Users on partner.UserId equals user.PartnerId
                join location in Locations on patner.UserId equals location.PartnerId
                where partner.UserId == 1
                select new { PartnerId = partner.PartnerId, PartnerName = user.Name, Lat = location.Lat, Lon = location.Lon };

by passing userid=1 as parameter I am getting this result:

partnerid  patnername      lat            lon
  2         venkat         14.00         12.00
  3         venkat         14.00         14.23

by observation of above result here partnernames are wrong for partnerid = 2 - patname was venu but displaying "venkat"

For partnerid = 3, partnername was raghu but displaying venkat.

How to display the correct partner names?

Upvotes: 0

Views: 86

Answers (1)

marc_s
marc_s

Reputation: 754488

I believe this JOIN here is wrong:

var result = from partner in Partners
             join user in Users on user.UserId equals partner.PartnerId

You're joining a user on his userId to a partner using his PartnerID.

Don't you need to join a user to a partner using PartnerID in both cases? Something like this:

var result = from partner in Partners
             join user in Users on user.PartnerId equals partner.PartnerId

Upvotes: 1

Related Questions