InsertAllOnSubmit creating duplicate entities in related tables RRS feed

  • Question

  • I am having a problem with the InsertAllOnSubmit creating duplicate entities in tables related to the one I am inserting to.


    I have two tables: one record in EquipmentService can be related to many records in TestStandard.  The problem comes when inserting new test standards.  Despite the fact that a test standard has been added to the EntitySet for an existing EquipmentService (with the code oEquipmentService.TestStandardServices.Add(oService) ), when the changes are submitted, a new EquipmentService record is added to that table as well.  I hope I am explaining this clearly.  In other words, if I have a new TestStandard entity with TestStandard.EquipServiceID = 1, when it is inserted into the database, its EquipServiceID is now 2, and there is a new record in EquipmentService that is a duplicate of record 1 except that it has an ID of 2!  The problem gets propagated upward - all the tables that were loaded with EquipmentService now have duplicate records in them as well.


    I have tried detaching the TestStandard by saying oTestStandard.EquipmentService = Nothing, but this clears out the value of EquipServiceID in TestStandard as well; if I try to set the value again later, I get an error.


    I have found similar code snippets posted online, that work fine according to those who have posted them, and I can't figure out what I am doing differently from them.  Can anyone help?  Thanks.


    Here is the code that causes the issue:

    Public Shared Function SaveServiceHistory(ByRef oServiceHistory As List(Of EquipmentService)) As Boolean

    Using db As myDataContext = DataHelper.GetDatabaseData


       db.EquipmentServices.InsertAllOnSubmit(oServiceHistory.Where(Function(es) es.IsDirty And es.EquipServiceID < 0))

       db.EquipmentServices.AttachAll(oServiceHistory.Where(Function(es) es.IsDirty And es.EquipServiceID >= 0), True)

       For Each oService In oServiceHistory

          db.TestStandards.InsertAllOnSubmit(oService.TestStandards.Where(Function(ts) ts.IsDirty And ts.TestStandardID = Nothing))  <-- this is the line I am having problems with

          db.TestStandards.AttachAll(oService.TestStandards.Where(Function(ts) ts.IsDirty And ts.TestStandardID > 0))



       Return True

    Catch ex As Exception

       Return False

    End Try

    End Using

    End Function


    Thursday, October 30, 2008 9:53 PM

All replies