2016-11-25 53 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