LINQ to SQL Join和If Condition

问题描述

| 我在下面有一个查询,如果bstock不为null并且bstock.Price(bstock.Price是可为null的doubel?)不为null,我想在其中设置价格。该联接是左外部联接。有人能帮我吗?
var bstocks = (from p in qry
                             join bstock in bstockRepository.Select() on p.StockCode equals bstock.StockCode
                             into J1
                             from bstock in J1.DefaultIfEmpty()
                             select new
                             {
                                 p.StockCode,p.Description,p.ListPrice,p.Price =  bstock.Price != null ? bstock.Price : p.Price,p.QuantityOnHand,p.Cube,p.ShippingFormat,p.Weight,p.NextShipment,p.NextShipment2,p.NextShipmentQuantity,p.NextShipment2Quantity,Bstock = p.Bstock
                             }
                              ).AsQueryable();
    

解决方法

        由于正在运行左联接,因此查询中的“ 1”可以为空。因此,您需要考虑以下因素:
Price =  bstock != null && bstock.Price != null ? bstock.Price : p.Price,
结果:
var bstocks = (from p in qry
                join bstock in bstockRepository.Select() on 
                    p.StockCode equals bstock.StockCode into J1
                from bstock in J1.DefaultIfEmpty()
                select new
                {
                        p.StockCode,p.Description,p.ListPrice,Price =  bstock != null && bstock.Price != null ? bstock.Price : p.Price,p.QuantityOnHand,p.Cube,p.ShippingFormat,p.Weight,p.NextShipment,p.NextShipment2,p.NextShipmentQuantity,p.NextShipment2Quantity,Bstock = p.Bstock
                    });