将自定义方法集成到LINQ to Entities查询中

时间:2012-06-22 21:56:02

标签: asp.net-mvc-3 linq entity-framework linq-to-entities

我有一个自定义方法,可以对一组数据执行一些计算:

 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语法,但还有其他类似的东西可以做吗?

1 个答案:

答案 0 :(得分: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