2010-11-12 44 views
2

我使用L2S進行數據庫操作在我的asp.net MVC應用程序我已經在我的倉庫Linq中使用自定義功能查詢

(from pt in db.oaProjectTasks 
        where pt.ProjectID == ProjectID 
        join t in db.oaTasks on pt.TaskID equals t.TaskID 
        where t.ParentTaskID == null 
        let daypassed = GetDaysPassed(t.StartDate,t.Duration) 
        select new ChartTask{TaskNumber = t.TaskNumber,StartDate = t.StartDate, 
        DurationRemaining = t.Duration - daypassed,TaskDescription = t.Task, DaysPassed = daypassed,Duration = t.Duration }).ToList(); 
下面

下面的簡單查詢GetDayPassed方法的認定中

private int GetDaysPassed(DateTime StartDate, int Duration) 
     { 
      int retVal; 
      if ((DateTime.Now - StartDate).Days > 0) 
      { 
       if ((DateTime.Now - StartDate.AddDays(Duration)).Days > 0) 
       { 
        retVal = Duration; 
       } 
       else 
       { 
        retVal = (DateTime.Now - StartDate).Days; 
       } 
      } 
      else 
      { 
       retVal = 0; 
      } 
      return retVal; 
     } 

沒有編譯時錯誤,但是,當我執行代碼時,它給了我以下消息的invalidOperationException。

Could not translate expression 'Table(oaProjectTask).Where(pt => (pt.ProjectID == Invoke(value(System.Func`1[System.Int64])))).Join(Table(oaTask), pt => pt.TaskID, t => t.TaskID, (pt, t) => new <>f__AnonymousType5f`2(pt = pt, t = t)).Where(<>h__TransparentIdentifier2 => (<>h__TransparentIdentifier2.t.ParentTaskID == null)).Select(<>h__TransparentIdentifier2 => new 

我該如何解決這個問題?如果在查詢中調用方法是不允許的我怎麼能在Linq查詢中做一個簡單的計算而不是調用GetDayPassed方法?

回答

5

你可以試試這個:

(from pt in db.oaProjectTasks 
where pt.ProjectID == ProjectID 
join t in db.oaTasks on pt.TaskID equals t.TaskID 
where t.ParentTaskID == null 
select t) 
    .ToList() // T-SQL query will be executed here and result will be returned 
    .Select(t => new ChartTask { 
     TaskNumber = t.TaskNumber, 
     StartDate = t.StartDate, 
     DurationRemaining = t.Duration - GetDaysPassed(t.StartDate,t.Duration), 
     TaskDescription = t.Task, 
     DaysPassed = GetDaysPassed(t.StartDate,t.Duration), 
     Duration = t.Duration }); 

的問題是,Sql的Linq試圖翻譯您的自定義功能,T-SQL,並因爲它不知道該怎麼做,它會拋出異常。在我的情況下,Linq將構造查詢,執行它(在調用.ToList()之後),並且您的函數將作爲Linq調用到對象查詢中。