Filter

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

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
 
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
 
Back
Top