Tuesday, May 27, 2008

LinqDataSource error on Update or Insert

Here is a reminder for myself about a problem that happens, and I always end up having to search to remember the solution. When performing an update or insert on a LinqDataSource, say from a GridView you get the error "Could not find a row that matches the given keys in the original values stored in ViewState. Ensure that the 'keys' dictionary contains unique key values that correspond to a row returned from the previous Select operation."... Sounds complicated.

Well it isn't. Check that you have set the DataKeyNames property on the GridView with the column name of the primary key(s) of the LinqDataSource table. But that doesn't make sense, you say.

It does if you have a look at the stack trace. For example,
System.Web.UI.WebControls.LinqDataSourceView.GetOriginalValues(IDictionary keys) +926 System.Web.UI.WebControls.LinqDataSourceView.BuildUpdateDataObjects(Object table, IDictionary keys, IDictionary values, IDictionary oldValues) +102 System.Web.UI.WebControls.LinqDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +87 System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +78

The LinqDataSource is just like the old SqlDataSource - it needs to know how to lookup the row in the database table to work out what you have changed. If you don't tell it the keys to lookup in the table, how will it ever know which row you were editing? Once the DataKeyNames are specified those columns are used to find the original row in the database, compare and merge your update changes and commit them back to the row. Simple. Now I just have to remember "Set the DataKeyNames property"...

kick it on DotNetKicks.com Shout it

5 comments:

Unknown said...

Thanks, a lot.

Freeheel said...

Thanks very much

Erik K. said...

Works as advertised! Many thanks.

Erik K. said...

Forgot to mention: not only does it work on GridView but also on DetailsView. It may happen when the AutoGenerateRows property is set to false, and you specify the fields manually. In that case, in edit mode you need to set the DataKeyNames property.

Anonymous said...

tnx man. It really helped!!