2012-06-22 79 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