LINQ: you cannot insert a duplicate key string into the object 'dbo.tblOutstandingCompletions' with a unique index

I have an application (ASP.NET 3.5) that allows users to restart a specific process if necessary. The process inserts records into the MS SQL table. I have an insert in Try / Catch and ignore catch if the entry already exists (error in Title will be valid). This worked fine using ADO, but after I got together in LINQ, I noticed an interesting thing. If there are already entries in the table when restarting the process, any new entries will be rejected with the same error, even though there is no existing entry. The code is as follows:

            Dim ins = New tblOutstandingCompletion
            With ins
                .ControlID = rec.ControlID
                .PersonID = rec.peopleID
                .RequiredDate = rec.NextDue
                .RiskNumber = 0
                .recordType = "PC"
                .TreatmentID = 0
            End With

            Try
                ldb.tblOutstandingCompletions.InsertOnSubmit(ins)
                ldb.SubmitChanges()
            Catch ex As Exception
                ' An attempt to load a duplicate record will fail
            End Try

The DataContext for the database was set during page load.

, DataContext :

        ldb = New CaRMSDataContext(sessionHandler.connection.ToString)
        Dim ins = New tblOutstandingCompletion

, , - . DataContext , .

+3
3

, int, GUID newguid() - LINQ GUID, Guid.Empty, ( ) () .

, GUID . : http://www.doodle.co.uk/Blogs/2007/09/18/playing-with-linq-in-winforms.aspx

DataContext.

, InsertOnSubmit ( ), SubmitChanges?

+2

, DataContext , ​​ , , , , "" . , , , . LINQ . , , reset , .

+1

gfrizzle, , ...

, , . , , .

, :

        db = null;
        db = new NNetDataContext();

immediately after calling SubmitChanges (), which executes previous InsertOnSubmit requests. This seems to be silly, but this is the only way that works for me differently than redesigning the code.

+1
source

All Articles