Filter

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Condition 2
Linq. Please, need help. 1
Linq. Avoid Joins 2
Linq. Select 1
Linq. Aggregate 4
LINQ. Who knows how to do this? 2
Circular Reference. I really need help ... thanks. 4

Top