集成自定义的方法到LINQ到实体查询(Integrating custom method into

2019-07-30 02:33发布

我有,其对一组数据的一些计算的自定义方法:

 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语法,但有别的像这样,我还能做什么?

Answer 1:

你需要计算这样的百分比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调用函数更多信息查询这里 。



文章来源: Integrating custom method into LINQ to Entities query