Linq to Sql 左连接 , 取右表可能为 null的 int类型字段

linq to sql , linq to entity 遇到一个问题, 主表, 从表 一对一 关系,  主表有记录, 从表 可能没有记录. 

现在要查询 主表+从表 的某几个字段.

从表字段 有的是 Tzsbh  int? 类型.    int 转 string  如果对象为null,报错

                var queryLeft = from c in db.AA
                                join sr in
                                    (
                                     from ss in db.BB
                                     select ss
                                     )
                                   on c.Id equals sr.Sid
                                   into x
                                from y in x.DefaultIfEmpty()
                                select new { c.Id, c.timeflag, Tzsbh = y.Tzsbh };

                 result = from c in queryLeft.AsEnumerable()
                             select new ShowInfo
                             {
                                 Sid = c.Id,
                                
                                 timeflag = c.timeflag,
                                 PdfId = c.Tzsbh.ToString()  //int 转 string 这一行, 如果对象为null,报错
                             };

 尝试如下方案, 左连接, 1 对多, 取右边表 FirstOrDefault, 然后判断 null, 再进行取值

 var sg = db.AA.GroupJoin(db.BB, c => c.Id, d => d.Sid, (c, d) => new { c.Id, c.timeflag, Pdf = d.FirstOrDefault() }).Select(o => o);

 var result = from c in sg.AsEnumerable()
                             select new ShowInfo
                             {
                                 Sid = c.Id,
                                 timeflag = c.timeflag,
                                 PdfId = c.Pdf == null ? "" : c.Pdf.Tzsbh.ToString()
                             };
原文地址:https://www.cnblogs.com/mjxxsc/p/9083677.html