Error on Cout but i am not using Count in my LINQ exrpression,


Question

I am trying to return a set of data in JSON formate from a LINQ select ran against my EF Code First DB and am getting the error

Count must be a DbConstantExpression or a DbParameterReferenceExpression. Parameter name: count

but I am not sure why I am getting it as I am not using a COUNT parameter in my LINQ query so why am I getting this error?

    public ActionResult GetData(string sidx, string sord, int page, int rows)
    {
        try
        {
            //Get total rows
            int RowCount = db.Sections.Count();

            string OrderBy = (sidx + " " + sord);

            var SectionData = new
            {
                total = (int)Math.Ceiling((float)RowCount / (float)rows),
                page = page,
                records = RowCount,
                rows = (from s in db.Sections
                        select new
                        {
                            id = s.ID,
                            cell = new string[] {
                                SqlFunctions.StringConvert((double)s.ID).Trim(),
                                s.RouteName,
                                s.Title
                            }
                            .OrderBy(x => sidx)
                            .Skip(page * rows)
                            .Take(rows)
                        }).ToArray()
            };
            return Json(SectionData, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
            return Json(null, JsonRequestBehavior.AllowGet);
        }

    }

Accepted Answer

I'm not too familiar with EF, but I did come across an old msdn post where someone reported the same bug. They were performing a calculation inside .Skip() and to fix it they performed the calculation separately, and just used the result in their LINQ statement.

Try calculating page * rows first, then using that result in your LINQ statement:

var skipAmount = page * rows;

var SectionData = new
{
    ...
    ...
    rows = (from s in db.Sections
            select new
            {
                ...
                ...
                .OrderBy(x => sidx)
                .Skip(skipAmount)
                .Take(rows)

Popular Answer

Now with EF6 you can have lambda expressions in your Skip and Take parameters, and in fact its better to do so as the SQL Query is cached and re-used on subsequent pages: see this article

But you still need to have evaluated the parameter to pass as @Grant does. So the difference being

.Skip(() => skipAmount
.Take(() => rows)




Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why