I am having great difficulty updating an entity to my database using LINQ To SQL.
I am working on an MVC web site using Windsor Castle for my repositories. I am working with VS 2010 using the "Pro ASP.NET MVC Framework" book by Sanderson as a guide.
My problem is with the following code in my repository:
public void Save(Comment comment)
if (comment.CommentID == 0)
else if (m_commentsTable.GetOriginalEntityState(comment) == null)
The code is a direct copy of the book examples (which work correctly) but modified for my entity (Comment). m_commentsTable is of type Table<Comment>
This method is called for saving new Comment objects as well as updating existing ones. Saving new objects works fine, but updating existing objects fails when calling Attach with the following error:
"cannot add an entity with a key that is already in use."
I Googled the issue and found a lot of people with a similar problem. I tried many solutions, but none work.
- get the original object from the table and pass both old and new objects to Attach : e.g. Attach(comment, originalComment). I get the same error.
- pass 'true' as second arg to Attach. I get the following error: "An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy."
- pass 'true' as second arg to Attach after changing the UpdateCheck attribute on Comment's columns to Never. I get the original error.
Some forum posts suggested that I create another DataContext and attach my new object to it. This seems wasteful. Also, this would also entail saving my connection string (constructor arg). All that seems a bit messy and unnecessary.
Another suggestion was to add a version column to my table. This also seems wasteful and awkward. It makes me uncomfortable adding a column to a table to work around a data access problem.
Is there something I am missing? Does anyone have another suggestion that I haven't tried?
I am still mystified as to why the book examples work fine, but my 'copy' does not. I have a feeling I am missing something subtle, but have no idea what it is.
Should I give up on LINQ To SQL and try another approach? If so, what might that be?
Should I get over my discomfort and implement one of other suggestions (another DataContext or extra label column)?