2010-05-07 87 views
3

我正在爲客戶端開發一個小端應用程序,他們向我提供城市列表,並且必須將它們插入到數據庫中並關聯他們與他們的父母記錄。Linq to SQL - 如何在插入前驗證記錄

例子:

ID | PID | Region 
1   0   California 
2   1   Los Angeles 
3   1   San Fransisco 

現在我的代碼看起來像這樣

Dim input As StreamReader 
    Dim index As Integer 
    Dim filename As String 
    Dim RegionDC As New DAL.RegionsDataContext 



    For Each TextFile As String In Directory.GetFiles(Server.MapPath("~/app_data/business-trader cities/")) 
     input = File.OpenText(TextFile) 
     filename = New FileInfo(TextFile).Name 
     index = 0 


     ''# this is where we want to select the ID for the filename' 
     Dim _ID = (From R In RegionDC.bt_Regions _ 
       Where R.Region = filename.Replace(".txt", "") _ 
       Select R.ID).FirstOrDefault 

     While Not input.EndOfStream 

      Dim q = (From r In RegionDC.bt_Regions _ 
        Where r.Region = input.ReadLine() _ 
        Select r.ID).FirstOrDefault 

      ''# ***********************************' 
      ''# HERE IS WHERE IM TRYING TO VERIFY' 
      ''# IF THE RECORD EXISTS OR NOT' 
      ''# ***********************************' 

      ''# now we loop through the txt file' 
      ''# and insert the data into the database' 
      Dim oRegion As New DAL.bt_Region 
      oRegion.Region = input.ReadLine() 
      oRegion.FSSearchCount = 0 
      oRegion.WSearchCount = 0 
      oRegion.PID = _ID 

      RegionDC.bt_Regions.InsertOnSubmit(oRegion) 
      RegionDC.SubmitChanges() 

     End While 

     ''# clean up the locked files' 
     input.Close() 
     input.Dispose() 
    Next 

所以基本上如果洛杉磯是TXT文件,我不希望因爲它重新進入數據庫它已經存在。

任何人都可以幫我弄清楚如何在插入之前記錄已經存在嗎?

回答

1

假設沒有記錄可以有0的ID,我認爲這只是測試q = 0的問題。

但我認爲你在代碼中存在一個錯誤:在每次迭代中你都會調用input.ReadLine()兩次,因此你測試洛杉磯是否已經在數據庫中,然後嘗試插入舊金山。只需在變量中捕獲該行,然後使用該行。

1
if (RegionDC.bt_Regions.Any(r => r.Region == input.ReadLine())) 
{ 
    // Yes it exists 
} 
else 
{ 
    // No it doesn't exist 
} 

使用一個converter使VB版本:)

If RegionDC.bt_Regions.Any(Function(r) r.Region = input.ReadLine()) Then 
    ''# Yes it exists 
Else 
    ''# No it doesn't exist 
End If 
+0

@rockinthesixstring是你能算出這個?如果這個答案有助於你不忘記將其標記爲已接受的答案。 – Kelsey 2010-08-11 21:42:57