none
InsertOnSubmit and unique key RRS feed

  • Question

  •  

    I have an Table called say Customer ( it has a unique key contraint on Customer Name ) if I do ( with a non unique name )

     

    Using db As New BlogsDataContext()

    db.Customers.InsertOnSubmit(aCustomer)

    db.SubmitChanges()

    End Using

     

    If I catch the exception and display a nice message, the user then changes the customer name to something unique, and saves using code above you get.

     

    "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.  This is not supported."

     

    Any thoughts ?

    Sunday, April 27, 2008 7:49 AM

Answers

  • If you call the code you show again after the failure, you'll end up calling InsertOnSubmit twice.  That's likely where the exception is being thrown.  After you make your fixes you don't need to call InsertOnSubmit (or similar methods) again.  Just a new call to SubmitChanges is all you need.

     

    Monday, April 28, 2008 7:06 PM
    Moderator

All replies

  • Do you recreate aCustomer each time, or are you using the same object again ?

     

    Am wondering if it thinks aCustomer is already associated with a context.    try detaching it in the catch block.

    Monday, April 28, 2008 4:46 PM
  • If you call the code you show again after the failure, you'll end up calling InsertOnSubmit twice.  That's likely where the exception is being thrown.  After you make your fixes you don't need to call InsertOnSubmit (or similar methods) again.  Just a new call to SubmitChanges is all you need.

     

    Monday, April 28, 2008 7:06 PM
    Moderator