Strange LINQ Exception (Index out of bounds)

后端 未结 5 1101
天命终不由人
天命终不由人 2020-12-14 12:15

I have a table, we\'ll call Users. This table has a single primary key defined in SQL Server - an autoincrement int ID.

Sometimes, my LINQ

相关标签:
5条回答
  • 2020-12-14 12:23

    This almost certainly won't be everyone's root cause, but I encountered this exact same exception in my project - and found that the root cause was that an exception was being thrown during construction of an entity class. Oddly, the true exception is "lost" and instead manifests as an ArgumentOutOfRange exception originating at the iterator of the Linq statement that retrieves the object/s.

    If you are receiving this error and you have introduced OnCreated or OnLoaded methods on your POCOs, try stepping through those methods.

    0 讨论(0)
  • 2020-12-14 12:25

    I would say that you've got a model -> database mismatch somewhere. When I get as desperate as you on situations like this, I usually fire up VS.NET, create a new console app, and rebuild the section of the DBML which references the entity of interest in this query, and re-run. You may find that in this sort of isolation, the query works. Did you customize any of your entity definitions by filling out partial methods, especially the ones that fire on creation?

    0 讨论(0)
  • 2020-12-14 12:33

    This Problem Occurs due to linq object and Database fields of that Table are not identical.

    0 讨论(0)
  • 2020-12-14 12:36

    The exception occurs in a System library and your story makes me think the problem isn't in your code. Has the schema changed recently? Is your mapping correct?

    0 讨论(0)
  • 2020-12-14 12:43

    I had this Issue as well and solved it.

    Now I understand the error was wrong usage of Linq Data Context, but maybe my experience can still help others understand why they get this error.

    Linq Data Context is not meant for running simultaneously. Therefore creating multiple tasks running async is not ideal. Inspect following sample code to understand the issue:

    using(var ctx = new LinqDataContext())
    {
        List<Task> tasks = new List<Task>();
        for(int i=0;i<1000;i++)
        {
            var task = Task.Run(() => {
                var customer = ctx.Customers.SingleOrDefault(o => o.Id == i);
                customer.DoSomething();
            }
            tasks.Add(task);
        }
        Task.WaitAll(tasks);
    }
    

    In my scenario, I was passing the data context as a parameter in a longer call stack, and calling async methods along the way. So it wasn't as obvious as above example. But maybe this can help someone else anyhow :-)

    0 讨论(0)
提交回复
热议问题