如何处理多对多关系中的空值
how to handle null value in many to many relationship
我正在努力实现这样的目标:
如果有匹配的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 中有空值,那么这个查询仍然应该 运行。现在,它在数据库中不起作用,因为没有 post 为空 tagid 或 null 。如何做到这一点。有什么建议吗??
如果我没理解错的话,你需要像这样根据传入的参数动态构建过滤器
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
我正在努力实现这样的目标: 如果有匹配的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 中有空值,那么这个查询仍然应该 运行。现在,它在数据库中不起作用,因为没有 post 为空 tagid 或 null 。如何做到这一点。有什么建议吗??
如果我没理解错的话,你需要像这样根据传入的参数动态构建过滤器
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