2012-06-22 21 views
3

我有一組數據進行一些計算的自定義方法:集成自定義的方法到LINQ到實體查詢

private int GetPercentages(int OriginalValue, int TotalValue) 
     { 
      var newValue = (int)Math.Round(((decimal)OriginalValue/(decimal)TotalValue) * 100); 

      return newValue; 
     } 

我需要能夠運行的LINQ to Entities查詢裏面這個方法:

var data = from SurveyResponseModel in db.SurveyResponseModels 
         group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount 
         select new ResultsViewModel() 
         { 
          MemberId = resultCount.Key, 
          PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp), 
          PatientFollowUpResultPct = GetPercentages(db.SurveyResponseModels.Count(r => r.PatientFollowUp),totalResponsesResult), 
          ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice), 
    }; 

我需要在查詢中約20多行運行這個所以就堅持它內聯似乎不是一個很好的選擇。據我所知,它需要被轉換成SQL語法,但有別的像這樣,我還能做什麼?

回答

3

你需要做一個lambda表達式計算這樣的比例:

Expression<Func<int, int, int>> calcPercentage = 
    (OriginalValue, TotalValue) => (int)Math.Round(((decimal)OriginalValue/(decimal)TotalValue) * 100); 

而且使用這樣的:

var data = from SurveyResponseModel in db.SurveyResponseModels.ToExpandable() 
      group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount 
      select new ResultsViewModel() 
      { 
       MemberId = resultCount.Key, 
       PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp), 
       PatientFollowUpResultPct = calcPercentage.Invoke(db.SurveyResponseModels.Count(r => r.PatientFollowUp), totalResponsesResult), 
       ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice), 
      }; 

更多關於LINQ中調用函數信息查詢here

+0

嗯..表達是給我一個錯誤「代表system.func不採取2個參數」 – user547794

+0

@ user547794我改正了答案。表達類型應該是'Func鍵'這需要2'int'參數,並返回一個'int'。 –

+0

貌似表達的工作,但我發現了一個「有一些無效參數」的「calcPercentage.Invoke(db.SurveyResponseModels.Count(R => r.PatientFollowUp),totalResponsesResult)」 – user547794