如何处理多对多关系中的空值

时间:2016-02-04 18:08:35

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

我正在努力实现这样的目标: 如果有匹配的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的多个条件。只有一个参数值。表示如果id参数有值,则tagid将为null,如果tagid为null,则id将具有一些值。

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

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你需要根据传递的参数动态构建过滤器,如

// api/model/product.js
    getProductDetails:function(product_id){
        return new Promise(function(resolve, reject) {
            var product={},options=[];
            //details
          Product.query("select * from product p , product_description pd where p.product_id="+product_id+" and pd.product_id= p.product_id and pd.language_id=1",function(error, details) {
            //images    
            Product.query("SELECT * FROM product_image WHERE product_id = "+product_id+" ORDER BY sort_order ASC",function(error, images) { 

            //options   
            Product.query("SELECT * FROM product_option po LEFT JOIN `option` o ON (po.option_id = o.option_id) LEFT JOIN option_description od ON (o.option_id = od.option_id) WHERE po.product_id = "+product_id+" AND od.language_id = '1' ORDER BY o.sort_order",function(error, options) {
                    options.forEach(function (item) {
                                //options value
                              Product.query("SELECT * FROM product_option_value pov LEFT JOIN option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_id = "+product_id+" AND pov.product_option_id = "+item.product_option_id+" AND ovd.language_id = '1' ORDER BY ov.sort_order",function(error,option_value){
                                    options.push({options: item, option_value: option_value});
                                });
                        });//foreach option
                product={details:details[0], options: options, images:images};
                resolve(product);
            }); 

        });

        });

        }); 
    }