Linq to SQL - How to check record does not exist before insert

I am working on a small third-party client application in which they provide me with a list of cities, and I need to insert them into the database and link them to the parent records.

Example:

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

Now my code is as follows:

    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

So if Los Angeles is in a TXT file, I do not want it to be re-entered into the database, as it already exists.

Can someone help me figure out how to check if a record exists before insertion?

+3
source share
3 answers

LINQ To SQL Samples - EXISTS / IN / ANY / ALL

Public Sub LinqToSqlExists01()
    Dim q = From c In db.Customers _
            Where Not c.Orders.Any()

    ObjectDumper.Write(q)
End Sub
+2
source

, 0, , q = 0.

, : input.ReadLine() , , - , -. , .

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

A converter is used to make a version of VB :)

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

Source: https://habr.com/ru/post/1744560/


All Articles