Linq to Sql - How do I clear objects from data context change tracking? RRS feed

  • Question

  • Update -- I think I found the answer.  I need to create more short-lived datacontexts -- I was trying to have just one.


    I've got a subroutine that attempts to add a new item to a table.  The table has a constraint disallowing duplicate names -- here is the code:code is below.  I can successfully add new categories UNTIL I try to add a duplicate -- which gets the expected error message.  After than, any category, even if it has a valid, non-duplicative name, gets the same error message indicating that the unique name constraint is being violated. I have to close & restart my app to be able to add categories.

    Reading the documentation leads me to believe that this is because the invalid (duplicate) category is still in the datacontext stash of objects to track -- is there a way to get rid of it?? Thanks!

    private sub btnAddForm

    dim dlg as new adder






       Dim newCategory As Category = New Category(Guid.NewGuid(), dlg.CatName)






    Catch ex As Exception


    'MsgBox("Database not updated. Possible duplicate name.")


    End Try


    End If


    End Sub

    If dlg.DialogResult = Windows.Forms.DialogResult.OK Then
    Wednesday, May 18, 2011 7:51 PM


  • Hi mtk_programmer,

    Thank you for your post.


    AFAIK, there is currently no way to update an existing DataContext with the current content of the database. However, you can call DataContext.Refresh on a particular object that you have previously read. Mark sure that you consider the refresh mode because requiring can overwrite any changes that may have been made on the client before requerying. I suggest you can create a new DataContext. Here’s an article discussed this topic.


    Hope this helps.

    Best Regards,

    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, May 20, 2011 3:39 PM