Filter

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • shapper

    Filter

    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.Whe re(pt =pt.Tag.Name == tag ||
    tag == null).Select(pt =pt.Tag).Defaul tIfEmpty()
    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
  • shapper

    #2
    Re: Filter

    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.Whe re(pt =pt.Tag.Name == tag ||
    tag == null).Select(pt =pt.Tag).Defaul tIfEmpty()
                 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.Sel ect(pt =>
    pt.Tag).Default IfEmpty()
    orderby p.UpdatedAt
    descending
    where p.PostsTags.Whe re(pt =pt.Tag.Name ==
    tag || tag == null).Count() != 0

    I think this is ok.

    Thanks,
    Miguel

    Comment

    Working...