LINQ to SQL: Selecting a one-to-many relationship
I've got two tables (articles and tags) that have a one-to-many relationship.
I remember seeing somewhere that I can create nested objects/arrays/etc from that relationship. The output of which I would like in a format such as (in JSON format):
{1 : {
id : 1,
title : 'article title',
开发者_运维知识库 tags : ({
id : 16,
tagname : 'first tag'
},{
id : 23,
tagname : 'another tag'
})
}
I'm creating an internal knowledge base system with a list view similar to the front page of stack overflow (that's the way I'd like to display the tags).
How would I go about doing this? A subquery? Thanks.
If I understand your question correctly you're looking for the SelectMany
function which lets you 'unroll' nested structures like yours. SelectMany
is indeed executed in Query syntax by a sub-query:
IEnumerable<Tag> =
from article in Articles
from tag in article.Tags
select tag;
In method form:
IEnumerable<Tag> tags = Articles.SelectMany(a => a.Tags);
精彩评论