开发者

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?


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.


In theory, you should always use Join, if nothing else, then for clarity and readability. But in any 1:M case, you need to specify how the tables relate to each other. Just as you would have to do in SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜