By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,986 Members | 2,042 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,986 IT Pros & Developers. It's quick & easy.

Filter

P: n/a
Hello,

I have 3 tables:
Posts (PostID, ...)
PostsTags (PostID, TagID)
Tags (TagID, Name)

PostsTags associate each post to one or many tags.

I need to select all posts associated to a tag given the tag's name.
If the given tag's name is null then return all posts.

I have the following:

posts = (from p in database.Posts
let tags = p.PostsTags.Where(pt =pt.Tag.Name == tag ||
tag == null).Select(pt =pt.Tag).DefaultIfEmpty()
orderby p.UpdatedAt descending
select new PostLeaf {
Post = p,
Tags = tags.ToList(),
TagsCSV = string.Join(", ", tags.Select(t =>
t.Name).ToArray())
}).ToPagedList(page.HasValue ? page.Value - 1 : 0,
PageSize);

When I run this code with a certain tag what I get ALL posts. They are
not filtered.
However, all the posts that are not associated to that tag their
TagsCSV property is empty.

What am I missing here?

Thanks,
Miguel
Nov 18 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Nov 18, 5:20*pm, shapper <mdmo...@gmail.comwrote:
Hello,

I have 3 tables:
Posts (PostID, ...)
PostsTags (PostID, TagID)
Tags (TagID, Name)

PostsTags associate each post to one or many tags.

I need to select all posts associated to a tag given the tag's name.
If the given tag's name is null then return all posts.

I have the following:

*posts = (from p in database.Posts
* * * * * * *let tags = p.PostsTags.Where(pt =pt.Tag.Name == tag ||
tag == null).Select(pt =pt.Tag).DefaultIfEmpty()
* * * * * * *orderby p.UpdatedAt descending
* * * * * * *select new PostLeaf {
* * * * * * * * *Post = p,
* * * * * * * * *Tags = tags.ToList(),
* * * * * * * * *TagsCSV = string.Join(", ", tags.Select(t =>
t.Name).ToArray())
* * * * * * * }).ToPagedList(page.HasValue ? page.Value - 1: 0,
PageSize);

When I run this code with a certain tag what I get ALL posts. They are
not filtered.
However, all the posts that are not associated to that tag their
TagsCSV property is empty.

What am I missing here?

Thanks,
Miguel
I made it work as follows:

let tags = p.PostsTags.Select(pt =>
pt.Tag).DefaultIfEmpty()
orderby p.UpdatedAt
descending
where p.PostsTags.Where(pt =pt.Tag.Name ==
tag || tag == null).Count() != 0

I think this is ok.

Thanks,
Miguel
Nov 18 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.