linq to sql 左联接出错,未将对象引用设置到实例

            var result = from a in model
                         join b in orderDetailModel on a.FoodMenuID equals b.FoodMenuID into g
                         from b in g.DefaultIfEmpty()
                         select new Model.WebApiModel.WMFoodMenu
                         {
                             BarginPrice = a.BarginPrice,
                             Credits = a.Credits,
                             FoodMenuCategoryID = a.FoodMenuCategoryID,
                             FoodMenuID = a.FoodMenuID,
                             RestaurantID = a.RestaurantID,
                             FoodMenuName = a.FoodMenuName,
                             SaleCount = b != null ? b.FoodMenuSaleCount : 0,
                             ImgUrl100 = a.ImgUrl100,
                             ImgUrl150 = a.ImgUrl150,
                             IsRecommend = a.IsRecommend,
                             Price = a.Price
                         };

 这里,必须要注意一点是:SaleCount = b != null ? b.FoodMenuSaleCount : 0,这里如果SaleCount字段不允许为空,必须先判定。

如果写成 SaleCount = b.FoodMenuSaleCount,当右边数据为空时,将出现未将对象引用设置对实例的错误

你可能感兴趣的:(linq to sql 左联接出错,未将对象引用设置到实例)