2016-11-25 65 views
-3

我正在研究一个Sindows Forms应用程序,以帮助保持一些扫描仪的库存。我正在使用Linq2Sql,每个表都有一个id列。在我的维修历史表格上。我正在尝试使用库存表中的序列号,以便它进入数据库并从表中查找sID并返回正确的值,但是当我将所有输入的数据发送到历史表时,它会得到一个空引用异常。vb.net form linq nullreferenceexception

Dim db As New DataClasses1DataContext 
Dim rep As Scanner_Repair_History 

Dim scan = (From Scanner_Inventory In db.Scanner_Inventories Where scannerid.Text = Scanner_Inventory.SN Select Scanner_Inventory.SID).FirstOrDefault 

rep.SID = scan 
rep.Date_Broken = datebroke.Value 
rep.Description = description.Text 
rep.Send_Date = senddate.Text 
rep.Recieve_Date = recievedate.Text 
rep.Cost = cost.Text 
rep.PlantID = plantid.Text 
rep.BID = brokenid.Text 
rep.RMAnumber = rmanum.Text 

db.Scanner_Repair_Histories.InsertOnSubmit(rep) 
db.SubmitChanges() 
+2

的【什么是一个NullReferenceException,如何解决呢?(可能的复制http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do- i-fix-it) – Bugs

回答

0

是我,但你没有实例化你的“代表”可变

0

你不必放置一个“新”的关键字定义的对象,但我也很好奇,如果它是一个系统类型。

根据Jinx88909更新 您可能正在返回可能为空且具有null属性的整个POCO对象。如果您使用的是.NET 4.5及更高版本,则可以通过执行空值条件来调整此次数。 '?'。运营商。

Dim db As New DataClasses1DataContext 
'I need to be a new object and not instantiated as Nothing 
Dim rep As New Scanner_Repair_History 

'You have the potential for a nothing value here as 'FirstOrDefault' includes a potential Nothing'. 
'I would get the entire object and then just a property of it after the fact 
Dim scan = (From Scanner_Inventory In db.Scanner_Inventories Where scannerid?.Text = Scanner_Inventory?.SN Select Scanner_Inventory).FirstOrDefault?.Sid 

If scan IsNot Nothing Then 
    rep.SID = scan 'Could you maybe want scan.Id or something similar? 
    rep.Date_Broken = datebroke.Value 
    rep.Description = description.Text 
    rep.Send_Date = senddate.Text 
    rep.Recieve_Date = recievedate.Text 
    rep.Cost = cost.Text 
    rep.PlantID = plantid.Text 
    rep.BID = brokenid.Text 
    rep.RMAnumber = rmanum.Text 

    db.Scanner_Repair_Histories.InsertOnSubmit(rep) 
    db.SubmitChanges() 
Else 
    Console.WriteLine("I got nothing for you with the inputs you put in!") 
End If 
+0

使用isnot只是跳到插入到表中。 从我可以告诉当我开始程序'代表'指向'Scanner_Repair_History'表像它的假设,但当它跳过查询'代表'变成'没有'。我不完全确定原因是什么。和'扫描'确实会为扫描仪SN返回正确的ID – Johnathan