Search code examples
linqlinq-to-sql

Linq - Join Confusion


For the sake of this question, let's assume I have tables 'A' and 'B' and there is a 1:1 relationship between them. In a Linq query, I can do the following:

from row in A
where row.B.Description = someValue
select A

Where row.B is the reference to table 'B'.

However, let's now assume there is a 1:M relationship between 'A' and 'B'. The above query no longer works. It seems I need to explicitly use 'join' as follows:

from row in A
join row1 in B on row.BId = row1.BId
where row1.Description = someValue
select A

My question is this. Am I correct that for 1:M relationships, 'join' is required? Or is there are way to do this query, without using join, like in the 1:1 case?


Solution

  • You don't have to join explicitly, select many will do the trick

    from row in A   
    from row1 in row.B  
    where row1.Description == someValue   
    select row  
    

    alternatively (although I really don't like it)

    from row in A
    where row.B.Any(b => b.Description == someValue)
    select row
    

    With the first option you will need to do a Distinct() on the result if there are many B's that have the same description.