开发者

Condensing linq expressions into one expression for a simple blog system

I currently have many linq expressions nested within foreach loops ... kind of defeating the point of using linq!

What I'm trying to achieve is a simple blog model (blog posts which have multiple tags and are associated with multiple categories... that's all).

I'm looking for a way to condense all my linq expressions into a single expression, and the way I'm attempting to do it at the moment isn't returning desired results. Here's a basic representation of what I'm trying at the moment:

var blogs = 
    from blog in db.BlogPosts
    join categories in db.BlogCategories
        on blog.Fk_Category_Id equals category.Id
    // Using 开发者_如何学Pythona junction table because blogs can have multiple tags,
    // and tags can be shared across different blogs.
    join juncTags in db.Junc_BlogTags
        on blog.Id equals juncTags.Fk_BlogPost_Id
    join tags in db.Tags
        on juncTags.FK_Tag_Id equals tags.Id
    select new
    {
        blog,
        categories,
        tags
    };

foreach(var blog in blogs)
{
    blog.blog // Correct, can obtain information of current blog...
    blog.categories // Correct, shows the information of Blog's category
    blog.tags // Wrong, only refers to the first tag - next itteration will 
    // show the same blog with the next tag .. not what I want.
}

I'm sure that its something simple that I'm missing here, but can't figure it out and thought that Stack Overflow would be able to answer this easily.

Thanks in advance!


It's not clear exactly what you'd prefer to get instead of what you're currently getting, but how about this?

var blogs = from blog in db.BlogPosts
            join categories in db.BlogCategories
                on blog.Fk_Category_Id equals category.Id
            select new
            {
                blog,
                categories,
                tags = from juncTags in db.Junc_BlogTags
                       join tags in db.Tags
                           on juncTags.FK_Tag_Id equals tags.Id
                       where juncTags.Fk_BlogPost_Id = blog.Id
                       select tags
            };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜