1

我在视图中使用 MVC 平台和 jqGrid。下面是控制器代码返回 json 到网格的部分

IQueryable<CalendarViewModel> callendars =
            from call in (new KYTCDataContext()).Calendars
            where call.AcademicYear == id
            select Matcher.Calendar(call);

        if (jqGridParameters._search != false)
        {
            callendars = callendars.Where(jqGridParameters.WhereClause);
        }

        if (jqGridParameters.sidx != null)
            callendars = callendars.OrderBy(
                jqGridParameters.sidx.Substring(8) + " " + jqGridParameters.sord.ToLower());
        var count = callendars.Count();
        int pageIndex = jqGridParameters.page;

Matcher 是一个静态类。下面是该类的使用方法

public static class Matcher
    { 
public static CalendarViewModel Calendar(Calendar call)
        {
            return new CalendarViewModel
            {
                ID = call.ID,
                Name = call.Name,
                StartDate = call.StartDate,
                EndDate = call.EndDate,
                AcademicYear = call.AcademicYear
            };
        }
}

在线

var count = callendars.Count();

我收到此错误:

方法 'KYTC.Models.CalendarViewModel Calendar(KYTC.Data.Calendar)' 不支持对 SQL 的转换。

但是当我将 LINQ 查询更改为此:

IQueryable<CalendarViewModel> callendars =
            from call in (new KYTCDataContext()).Calendars
            where call.AcademicYear == id
            select new CalendarViewModel
            {
                ID = call.ID,
                Name = call.Name,
                StartDate = call.StartDate,
                EndDate = call.EndDate,
                AcademicYear = call.AcademicYear
            };

我的代码运行良好。

我的班级定义有什么问题?

4

1 回答 1

0

您的类定义没有任何问题。问题是您根本无法在 Linq-to-SQL(或 EntityFramework)查询中调用任意函数。只有少数预定义的方法可以转换为 SQL 语法。您的最终方法是CalendarViewModel从查询中返回对象的正确方法。

但是,您也可以这样做:

public static Expression<Func<Calendar, CalendarViewModel>> CalendarExpression()
{
    return c => new CalendarViewModel
    {
        ID = c.ID,
        Name = c.Name,
        StartDate = c.StartDate,
        EndDate = c.EndDate,
        AcademicYear = c.AcademicYear
    };
}

var calendarExpr = Match.CalendarExpression();
IQueryable<CalendarViewModel> callendars =
    (from call in (new KYTCDataContext()).Calendars
     where call.AcademicYear == id
     select call)
    .Select(calendarExpr);
于 2013-03-28T15:53:55.450 回答