【问题标题】:how to handle null value in many to many relationship如何处理多对多关系中的空值
【发布时间】:2016-05-14 12:02:35
【问题描述】:

我正在尝试实现这样的目标: 如果有匹配的 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 子句包含多个我要过滤帖子的条件。只有一个参数具有值。表示如果 id 参数有值,则 tagid 将为空,如果 tagid 为空,则 id 将有一些值。

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

【问题讨论】:

  • 请重新表述问题。当idnull 时会发生什么?当tagIdnull?绕过相应的条件?
  • @IvanStoev 我已经编辑了最后的问题,请看一下

标签: asp.net-mvc linq many-to-many null-coalescing-operator


【解决方案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

【讨论】:

  • 嗯,它会工作我之前尝试过,但我正在寻找任何解决方案与空合并运算符顺便说一句我的支持 thnk u
  • @duke null 合并和其他“嵌入式”参数检查技巧会生成非常糟糕的 SQL 查询。我建议您在有动态过滤的任何时候使用上述方法 - 它只“花费”几行代码,但会产生最佳的更快查询。
  • 感谢您的回复,主要原因是我尝试使用空合并运算符,因为我认为如果您说使用 if 语句会导致更快的优化查询,那么我肯定会使用它们@伊万·斯托耶夫
猜你喜欢
  • 2021-01-28
  • 2020-10-09
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
相关资源
最近更新 更多