【问题标题】:Error on Cout but i am not using Count in my LINQ exrpression,计数错误,但我没有在我的 LINQ 表达式中使用计数,
【发布时间】:2013-12-27 10:26:29
【问题描述】:

我正在尝试从针对我的 EF Code First DB 运行的 LINQ 选择中返回一组 JSON 格式的数据,并收到错误

Count 必须是 DbConstantExpression 或 DbParameterReferenceExpression。参数名称:计数

但我不确定为什么会得到它,因为我没有在我的 LINQ 查询中使用 COUNT 参数,所以为什么会出现这个错误?

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

    }

【问题讨论】:

  • 您正在使用 RowCount 作为总数....我认为这不是问题,但确实可以计算。

标签: c# linq-to-entities asp.net-mvc-5 entity-framework-6


【解决方案1】:

我对 EF 不太熟悉,但我确实遇到了 old msdn post,有人报告了同样的错误。他们在 .Skip() 内部执行计算,为了解决这个问题,他们单独执行了计算,并在他们的 LINQ 语句中使用了结果。

先尝试计算page * rows,然后在您的 LINQ 语句中使用该结果:

var skipAmount = page * rows;

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

【讨论】:

  • 是的,这就是问题所在。制作了一个名为“SkipCount”的新变量来进行数学运算并将其放在Skip() 中并且它起作用了。谢谢
【解决方案2】:

现在使用 EF6,您可以在 Skip 和 Take 参数中使用 lambda 表达式,事实上这样做更好,因为 SQL 查询被缓存并在后续页面上重复使用:see this article

但是您仍然需要像@Grant 那样评估要传递的参数。所以区别是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    相关资源
    最近更新 更多