I am trying to insert a record into a table using Linq but get the dreaded Cannot add an entity with a key that is already in use error
'If the same data exists for the same patient in a record less that 21 days old then drop it
Dim RecordLookup As Integer = 0
RecordLookup = (From rc In CDEvodb.RISKCHANGEs _
Where rc.NHI = tmpNHI And _
rc.RECDATE > Date.Now.AddDays(-21) And _
rc.BPSYS = Convert.ToDecimal(Drow.Item("BPSYS")) And _
rc.CHOL = Convert.ToDecimal(Drow.Item("CHOL")) And _
rc.HDL = Convert.ToDecimal(Drow.Item("HDL"))).Count()
If (RecordLookup = 0) Then
Dim riskchange As New RISKCHANGE
riskchange.NHI = Drow.Item("NHI")
riskchange.RECDATE = Date.Now.Date()
riskchange.RISK = CalculatedRisk
riskchange.BPSYS = Drow.Item("BPSYS")
riskchange.CHOL = Drow.Item("CHOL")
riskchange.HDL = Drow.Item("HDL")
Try
CDEvodb.RISKCHANGEs.InsertOnSubmit(riskchange)
Catch ex As Exception
myLogging.OutputError("<" & DateTime.Now.ToString & "> " & "Error - creating risk change record in dataset for patient " & Drow.Item("NHI").ToString() & " - " & ex.Message)
End Try
End If
Basically I lookup on the table for a matching record (not including the Identity field) that is less than 21 days old. If I don't find one I create an instance of a row and set to insert it.
The SubmitChanges function is call a few lines down.
Drow is a DataRow from a Dataset previously populated using an SQLClient connection (the reason being I have not full converted over to Linq yet, just doing new functionality for now).
Cheers in advance.