Stan
Stan

Reputation: 26511

LINQ: Problem using DB with relations

I don't know how can I return posts to my view where their tags are equal to those who are passed to controller action.
I think there is some clever and easy way of doing this but I am very new to LINQ and SQL. DB

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?
}

Upvotes: 0

Views: 80

Answers (2)

David Fox
David Fox

Reputation: 10753

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;

Upvotes: 3

Quintin Robinson
Quintin Robinson

Reputation: 82335

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.

Upvotes: 0

Related Questions