2013-03-28 47 views
1

我在視圖中使用了MVC平臺和jqGrid。下面是控制器代碼返回JSON到電網方法x在使用靜態類時沒有支持的SQL轉換

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月曆(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 
      }; 

我的代碼運行良好。

我的班級定義有什麼問題?

回答

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); 
+0

非常感謝你,我有很多現在在我的代碼chaning的==>去上班。 – 2013-03-29 14:27:01

相關問題