开发者

LINQ: Problem using DB with relations

开发者 https://www.devze.com 2023-03-23 20:39 出处:网络
I don\'t know how can I return posts to my view where their tags are equal to those who are passed to controller act开发者_如何学JAVAion.

I don't know how can I return posts to my view where their tags are equal to those who are passed to controller act开发者_如何学JAVAion.

I think there is some clever and easy way of doing this but I am very new to LINQ and SQL.

LINQ: Problem using DB with relations

Code

// id = tag name, not it's id
public ActionResult Tag(string id)
{
    // I get all the PostTags where PostTags.Tag.Name = id
    var postTags = _db.PostTags.Where(x => x.Tag.Name == id);

    // And what I do now?
}


Using joins in relational data is easier to grasp as a novice using query syntax instead of extension methods. The following is possible with extension methods (like .Join(...), etc), but this is closer to the SQL you might already be used to.

var postTags = from t in _db.Tags
               join pt in _db.PostTags on t.ID equals pt.TagID
               join p in _db.Posts on pt.PostID equals p.ID
               where t.Name == id
               select p;


Well to select them you could do something similar to..

var posts = _db.Posts.Where(post => post.PostTags.Any(postTag => postTag.Tag.Name == id));

This will just select all Posts where any of the related PostTags has a Tag with the name passed.

0

精彩评论

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