当使用静态类时,方法x不支持转换为SQL
本文关键字:不支持 转换 SQL 方法 静态类 | 更新日期: 2023-09-27 18:06:30
我在视图中使用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;
匹配器是静态类。下面是类
使用的方法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
};
我的代码运行良好。
我的类定义有什么问题?
您的类定义没有问题。问题是,您根本无法在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);