Linq to sql Linq to SQL-如何验证记录不存在';t在插入之前存在
我正在为一个客户开发一个小应用程序,他们向我提供一个城市列表,我必须将它们插入数据库,并将它们与他们的父记录关联起来 例如:Linq to sql Linq to SQL-如何验证记录不存在';t在插入之前存在,linq-to-sql,Linq To Sql,我正在为一个客户开发一个小应用程序,他们向我提供一个城市列表,我必须将它们插入数据库,并将它们与他们的父记录关联起来 例如: ID | PID | Region 1 0 California 2 1 Los Angeles 3 1 San Fransisco 现在我的代码看起来像这样 Dim input As StreamReader Dim index As Int
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文件中,我不希望它重新输入数据库,因为它已经存在了
有人能帮我弄清楚如何在插入之前验证记录是否已经存在吗?假设没有记录的ID为0,我认为这只是测试
q=0
是否存在的问题
<>但是我认为代码中有一个bug:在每次迭代中,你调用“代码>输入.RealLoad())/Cudio两次,所以你测试洛杉矶是否已经在数据库中,然后尝试插入旧金山。只需捕获变量中的行,然后使用它。
用于制作VB版本:)
@RockingtheSixstring你能弄明白吗?如果这个答案对你有帮助,别忘了把它标记为已接受的答案。
Public Sub LinqToSqlExists01()
Dim q = From c In db.Customers _
Where Not c.Orders.Any()
ObjectDumper.Write(q)
End Sub
if (RegionDC.bt_Regions.Any(r => r.Region == input.ReadLine()))
{
// Yes it exists
}
else
{
// No it doesn't exist
}
If RegionDC.bt_Regions.Any(Function(r) r.Region = input.ReadLine()) Then
''# Yes it exists
Else
''# No it doesn't exist
End If