如何在LINQ连接多个表时检查null?

时间:2014-09-04 09:47:41

标签: c# linq linq-to-sql linq-to-entities linq-to-objects

var Data = (from s in _context.PRD_RecipeItem.AsEnumerable()
            where s.RecipeID == _RecipeID
            from i in _context.Sys_ChemicalItem.Where(x => x.ItemID == s.ItemID).DefaultIfEmpty()
            from u in _context.Sys_Unit.Where(x => x.UnitID == s.UnitID).DefaultIfEmpty()
            from st in FinalStock.AsEnumerable().Where(x => x.ItemID == s.ItemID).DefaultIfEmpty()
            from sup in _context.Sys_Supplier.Where(x => x.SupplierID == (st==null? 0: st.SupplierID)).DefaultIfEmpty()
            select new PRDChemProdReqItem
            {
                ItemID = s.ItemID,
                ItemName = (i == null ? null : i.ItemName),
                RequiredQty = s.RequiredQty,
                RequiredUnit = s.UnitID,
                RequiredUnitName = (u == null ? null : u.UnitName),
                RequsitionQty = s.RequiredQty,
                ApproveQty = s.RequiredQty,
                ApproveUnit = s.UnitID,
                ApproveUnitName = (u == null ? null : u.UnitName),
                PackSizeName = "",
                PackQty = 0,
                SizeUnitName = "",
                RequisitionUnit = s.UnitID,
                RequisitionUnitName = (u == null ? null : u.UnitName),
                StockQty = (st == null ? null : (Math.Round(Convert.ToDecimal(st.ClosingQty), 2)).ToString()),
                SupplierID = (st == null ? 0 : st.SupplierID),
                SupplierName = (sup == null ? null : sup.SupplierName),
                ItemSource = "Via Requisition"
            }).ToList();

这是我的代码。当stnull时,我会收到System.Reflection.TargetException类型的例外情况。如何解决这个问题。在此先感谢。

1 个答案:

答案 0 :(得分:0)

为什么不使用join?这将处理您的空值。

在此处查看更多详细信息,包括源代码:http://msdn.microsoft.com/en-us/library/bb311040.aspx