简体   繁体   English

连接具有相同ID的2列时出现NullReferenceException

[英]NullReferenceException when Joining 2 Column with Same ID

The situation is that i am joining 2 column with same ID to End up with a Single Column Table and my problem is some Info dont have Contact so this line (b => b.InfoID == a.ID) returns null or false and it shows NullReferenceException Error, Can someone help me with my problem in Linq?? 情况是我加入2列具有相同的ID以结束单列表,我的问题是一些信息没有联系所以这一行(b => b.InfoID == a.ID)返回null或false它显示NullReferenceException错误,有人可以帮我解决我在Linq的问题吗?

This is what my Table show before 这就是我的表之前显示的内容

|     Name     |    Address   |     Cellphone    |     Email      | 
|     John     |     NY       |       n/a        |   johndoe@y.c  |
|     John     |     NY       |    123456781     |       n/a      |

And i want my output to be one liner combined 而且我希望我的输出组合成一个衬垫

|     Name     |    Address   |     Cellphone    |     Email      | 
|     John     |     NY       |     123456781    |   johndoe@y.c  |

This is my Linq that shows the Joined table but when Info doesnt have Contact yet, It returns NullReferenceError 这是我的Linq,它显示了Joined表,但是当Info还没有Contact时,它返回NullReferenceError

var an = (from a in db.Info  
              from b in db.Contact.Where(b => b.InfoID == a.ID && b.ContactTypeID == 56 && b.LogicalDelete == false).DefaultIfEmpty()
              from c in db.Contact.Where(c => c.InfoID == a.ID && c.ContactTypeID == 59 && c.LogicalDelete == false).DefaultIfEmpty()           
              where 
              select new
              {
                  a.ID,
                  a.LastName,
                  a.FirstName,
                  a.MiddleName,
                  Email = b.Values,
                  Cellphone = c.Values,
              }).ToList();

You should check if b or c object is null or not like this 您应该检查b或c对象是否为null或不是这样的

   var an = (from a in db.Info  
          from b in db.Contact.Where(b => b.InfoID == a.ID && b.ContactTypeID == 56 && b.LogicalDelete == false).DefaultIfEmpty()
          from c in db.Contact.Where(c => c.InfoID == a.ID && c.ContactTypeID == 59 && c.LogicalDelete == false).DefaultIfEmpty()           
          where 
          select new
          {
              a.ID,
              a.LastName,
              a.FirstName,
              a.MiddleName,
              Email = b==null? "" : b.Values,
              Cellphone = c==null? "" : c.Values,
          }).ToList();

You are using DefaultIfEmpty method so it is possible that object b or c could be null. 您正在使用DefaultIfEmpty方法,因此对象b或c可能为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM