DbLimitExpression Exception
Recently I was writing some code for one of my personal projects and I ran across this error in the first Entity Framework call I made – System.ArgumentException ‘DbLimitExpression’ requires a collection argument. Haven’t seen that one before. For anyone running into this issue here’s how I figured it out.
Here’s the code that was blowing up. It is fetching data from the database and grouping by the first character of the name so that I can build a tree structure grouped alphabetically.
var items = from item in db.Items where item.Parent == null group item by item.Name.FirstOrDefault() into g select new Group() { Name = g.Key, Count = g.Count();
Given that this is the first EF call I started taking a look at the data configurations to ensure that I had declared my nav properties correctly because I was referencing a relationship (Parent
). Everything seemed fine. A collection would indicate aggregation or enumeration so the grouping and counting stood out so I started commenting out lines. Turns out it is the FirstOrDefault
line. This isn’t surprising really since EF doesn’t support all the LINQ methods but FirstOrDefault
works normally.
Oh well, there’s always another way to solve the problem so I switch to simply using array syntax since names cannot be null. Now I get the error – LINQ to Entities does not recognize the method ‘Char get_Chars’. Wow, evidently none of the standard string functions are going to work here. While I don’t like using EF-specific calls it looks like I need to here. Since I want the first character of the name I use the DbFunctions.Left method. Now the call succeeds.
Ultimately I’m probably going to change up this code such that I don’t need the grouping anymore but at least I know what the issue is now.