Search code examples
asp.net-mvclinqmany-to-manynull-coalescing-operator

how to handle null value in many to many relationship


I am trying to achieve something like this: if there is a matching id then filter result according to it otherwise bypass the condition

.Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId)

but i am not getting correct syntax with many to many relationship:

    public JsonResult GetPost(int? id, int? tagid)
    {
    var ret = from data in db.Posts.Include(x => x.Tags)
                 .Include(x => x.Neighbourhood)
                 .OrderByDescending(x => x.PostedDate)
                 .Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId)
                 && x.Tags.Any(t => t.TagId == tagid))
                 .ToList()
                 select new
                  {
                      TagName = string.Join(",", data.Tags.Select(t => t.TagName)),
                      Message = data.Message,
                    // and other related stuff
                   }

here, as u can see,this where clause contains multiple conditions i want to filter post.There will be only one parameter with value. means if id parameter have value then tagid will be null and if tagid is null then id would have some value.

now, i want if there is null value in tagid then still this query should run. right now, its not working becoz in database, there is no post with empty tagid or null .how to do it. any suggestions??


Solution

  • If I understand correctly, you need to build the filter dynamically based on the passed parameters like this

    var posts = db.Posts
        .Include(x => x.Tags)
        .Include(x => x.Neighbourhood)
        .OrderByDescending(x => x.PostedDate);
    if (id != null)
        posts = posts.Where(x => x.NeighbourhoodId == id.Value);
    if (tagid != null)
        posts = posts.Where(x => x.Tags.Any(t => t.TagId == tagid.Value));
    var ret = from data in posts
        // ... the rest