Question

I am new to Linq. I am trying to query some data in MS SQL.

Here is my statement:

select * from booking
left outer join carpark
    on booking.bookingId = carpark.bookingId
where userID = 5 and status = 'CL'

When I run this in MS SQL, I get the expected result. How can I do this in Linq?

Thank you for your help.

Était-ce utile?

La solution

you need this:

var query = (from t1 in tb1
             join t2 in tb2 on t1.pKey = t2.tb1pKey into JoinedList
             from t2 in JoinedList.DefaultIfEmpty()
             where t1.userID == 5 && t1.status == "CL"
             select new 
             {
                  t1,
                  t2
             })
             .ToList();

Autres conseils

You can try to do left join this way :

from t1 in tb1
from t2 in tb2.Where(o => o.tb1pKey == t1.pKey).DefaultIfEmpty()
where tb1.userId == 5 && tb1.status == "CL"
select t1;

Usually when people say they want a "left outer join," that's just because they've already converted what they really want into SQL in their head. Usually what they really want is all of the items from table A, and the ability to get the related items from table B if there are any.

Assuming you have your navigation properties set up correctly, this could be as easy as:

var tb1sWithTb2s = context.tb1
    .Include(t => t.tb2s)       // Include all the tb2 items for each of these.
    .Where(t => t.userID == 5 and t.status = "CL");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top