Search code examples
c#entity-frameworkentity-framework-6.1

Entity Framework - simple operation gives Format exception - Index (zero based) must be greater than or equal to zero


Entity Framework is giving a pretty cryptic error message when I try to do a simple Add operation.

_context.Users.Add(new User
{
     DateJoined = DateTime.UtcNow
});
_context.SaveChanges();

FormatException:  Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

User inherits from IdentityUser from Microsoft.AspNet.Identity

I crossed check the database and model and I cant seem to identify what property is causing the problem. The models contains:

  1. ints, bools, and strings - get default values
  2. one non-nullable DateTime property (DateJoined) that I provide
  3. one nullable DateTime property
  4. one enum that correctly defaults to 0
  5. virtual ICollections

I don't undestand what property is causing the issue, how can I know more specifically? Could it be something else? The exception dialog doesnt contain the familiar link to view the inner exception.


Solution

  • To know more about what is going on, try to do the following:

    1) Add an Interceptor to see the underlying database operation. From the logs, you can see the INSERT command and probably see what is going on by comparing it to the table constraints.

    2) Put a breakpoint on the SaveChanges and see the tracked entities from the Context object. Make sure that this user is the only added entity and marked as dirty. From there you can also see its properties

    3) In you model, mark all non-mandatory properties as [NonMapped] one by one. Spot the problematic property this way. If those properties where inherited from the base class, you can mark them as NonMapped programmatically in your database configuration class.

    4) If non of the above works, try using LinqPad to do your insert (from 1) )and see if you get a better error message

    Hope this helps