SubmitChanges throws IndexOutOfRangeException
Here’s hoping that this will help someone else. I’ve been working on a project for the past few months using LINQ to SQL vs. a Legacy database (and I do mean “vs.”). Today I ran into updates on a particular table throwing IndexOutOfRangeExceptions.
All you’re trying to do is update some instance generated from a LTS table. Instead, you get an IndexOutOfRangeException from deep within Linq, particularly “System.Data.Linq.IdentityManager.StandardIdentityManager“.
Here’s what the context looks like:
“Views” is a table that maps SomeTypeID and SomeValueID into a ViewID. (The table isn’t actually named ‘Views,’ but the purpose is the same) This ViewID is instrumental in working with “Elements,” and we’re trying to change the values of a particular Element and put it back into the database.
Some code:
var ctx = new ExampleDataContext(); // get some element: var element = ctx.Elements.Where(e => e.ElementID == 1).First(); // set some property: element.SomeOtherValue = false; // attempt to save -- FAIL ctx.SubmitChanges();
No Big Deal, right? However executing this results in:
“System.IndexOutOfRangeException was unhandled
Message=”Index was outside the bounds of the array.”
Source=”System.Data.Linq”
StackTrace:
at System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager`3.TryCreateKeyFromValues(Object[] values, MultiKey`2& k)” (etc etc etc)
The Solution: I mentioned this was “legacy” database, right? Take a look at the Views table again. The database has SomeTypeID and SomeValueID as the primary keys of the table, but we’re treating ViewID as if it were a primary key – and apparently that’s what Linq to SQL doesn’t like.
So, changing the legacy database is out of the question for this particular project, however I can tell the Context how I want things to behave:
Remove the PrimaryKey=true attributes from SomeType and SomeValue, and add that on the ViewID property, and now LinqToSql handles the association correctly.


