2016-02-04 67 views
0

我想实现这样的空值: 如果有那么一个匹配的ID根据它过滤后的结果,否则绕过条件如何在多处理很多关系

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

,但我不得到了许多正确的语法一对多的关系:

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 
        } 

这里,就像你看到的,这个where子句中包含多个条件,我想筛选post.There将是唯一一个值参数。意味着如果id参数有值,那么tagid将为null,如果tagid为null,那么id会有一些值。

现在,我想如果tagid中有空值,那么这个查询仍然应该运行。现在,它没有在数据库中工作becoz,没有空的tagid或null的帖子,如何做到这一点。有什么建议么??

+0

过滤请重新表述的问题。 'id'为'null'时会发生什么?当'tagId'为'null'?绕过相应的条件? –

+0

@IvanStoev我已经编辑了这个问题在末端PLZ看看 – duke

回答

1

如果我理解正确的话,你需要建立动态的基础上传递的参数是这样

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

好吧,它会工作我以前尝试过它,但我正在寻找任何解决方案与空合并运营商btw upvote从我thnk u – duke

+1

@duke null合并和其他“嵌入式”参数检查技巧会生成非常差的SQL查询。我建议您在任何时候使用上述方法进行动态过滤 - 它“仅花费”几行代码,但会产生最佳的更快查询。 –

+0

为响应,我试图使用空合并运算符的主要原因becoz我认为这是很快,如果你说如果使用if语句会导致更快的最佳查询,那么我肯定会使用它们@Ivan Stoev – duke