Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
        }

    }
like image 890
Matthew Verstraete Avatar asked Nov 30 '22 11:11

Matthew Verstraete


1 Answers

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)
like image 167
Grant Winney Avatar answered Dec 06 '22 05:12

Grant Winney