Linq2Sql加入DefaultIfEmpty

时间:2016-06-27 18:14:48

标签: c# .net linq

我有2个表,我需要根据cid来抓取列,这两个表中的ClientID都是。我下面的代码用于显示表,但_DOCID始终为null。我错过了什么?

            public IQueryable ReturnCart(int cid)
    {
        try 
        {
            var result = from c in veps.ecomCarts
                         join d in veps.lawFirmClientDocumentPurchaseds on c.ClientID equals d.ID into cd
                         from d in cd.DefaultIfEmpty()
                         where c.ClientID == cid
                            select new
                         {
                             _DOCID = d.ID,
                             _ID = c.ID,
                             _CID = c.ClientID,
                             _UPC = c.UPC,
                             _Description = c.Description,
                             _Quantity = c.Quantity,
                             _UnitPrice = c.UnitPrice,
                             _Discount = c.Discount,
                             _Total = c.Total,
                             _InProgress = c.InProgress,
                             _dts = c.dts

                         };


            return result;
        }
        catch (Exception ex)
        {
            _IsError = true;
            _ErrorMsg = ex.Message;
            return null;
        }
    }

更新了问题图片: enter image description here

1 个答案:

答案 0 :(得分:0)

因此,经过多次思考,我意识到我的问题的答案是GroupBy Nested。这是我的最终代码。

public IQueryable ReturnCart(int cid)
    {
        try 
        {
            var result = (from c in veps.ecomCarts
                          where c.ClientID == cid
                          select new 
                          {

                              _ID = c.ID,
                              _CID = c.ClientID,
                              _UPC = c.UPC,
                              _Description = c.Description,
                              _Quantity = c.Quantity,
                              _UnitPrice = c.UnitPrice,
                              _Discount = c.Discount,
                              _Total = c.Total,
                              _InProgress = c.InProgress,
                              _dts = c.dts,

                              lcdp = from d in veps.lawFirmClientDocumentPurchaseds
                                     select new
                                     {
                                         _DOCID = d.ID
                                     }
                          });

            return result;
        }
        catch (Exception ex)
        {
            _IsError = true;
            _ErrorMsg = ex.Message;
            return null;
        }
    }

感谢Ivan的发帖。你实际上帮我想到了需要做的事情。所以,谢谢你。