【发布时间】:2020-06-07 09:20:14
【问题描述】:
我目前正在努力弄清楚如何通过仅具有 getter 的字段对查询进行排序。我有一个 IQueryable 正在构建如下:
var referrals = db.Referrals
.Include(x => x.Doctor)
.Include(x => x.OfficeLocation)
.Where(x => (vm.OfficeLocationSelection == -1 ? true : x.OfficeLocationId == vm.OfficeLocationSelection) &&
string.IsNullOrEmpty(vm.SearchTerm) ? true : x.Doctor.Name.ToLower().Contains(vm.SearchTerm.ToLower()))
.GroupBy(x => x.Doctor)
.Select(x => new ReferralGridRowViewModel
{
DoctorName = x.Key.Name,
January = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 1 && y.Date.Year == DateTime.Now.Year).Count(),
February = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 2 && y.Date.Year == DateTime.Now.Year).Count(),
March = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 3 && y.Date.Year == DateTime.Now.Year).Count(),
April = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 4 && y.Date.Year == DateTime.Now.Year).Count(),
May = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 5 && y.Date.Year == DateTime.Now.Year).Count(),
June = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 6 && y.Date.Year == DateTime.Now.Year).Count(),
July = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 7 && y.Date.Year == DateTime.Now.Year).Count(),
August = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 8 && y.Date.Year == DateTime.Now.Year).Count(),
September = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 9 && y.Date.Year == DateTime.Now.Year).Count(),
October = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 10 && y.Date.Year == DateTime.Now.Year).Count(),
November = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 11 && y.Date.Year == DateTime.Now.Year).Count(),
December = x.Where(y => y.DoctorId == x.Key.Id && y.Date.Month == 12 && y.Date.Year == DateTime.Now.Year).Count()
});
ReferralGridRowViewModel 如下所示(注意 YearToDate 属性):
public class ReferralGridRowViewModel
{
public string DoctorName { get; set; }
public int January { get; set; }
public int February { get; set; }
public int March { get; set; }
public int April { get; set; }
public int May { get; set; }
public int June { get; set; }
public int July { get; set; }
public int August { get; set; }
public int September { get; set; }
public int October { get; set; }
public int November { get; set; }
public int December { get; set; }
public int YearToDate {
get {
return (January + February + March + April + May + June + July + August + September + October + November + December);
}
}
}
当我尝试调用以下内容时:
referrals = referrals.OrderByDescending(x => x.YearToDate);
然后我收到以下异常:
LINQ to 不支持指定的类型成员“YearToDate” 实体。只有初始化器、实体成员和实体导航 支持属性。
当查询实际在这一行执行时:
referralRows = referrals.Skip(vm.Skip).Take(vm.PageSize).ToList();
我怎样才能以高效的方式克服这个问题?我宁愿不在 YearToDate 的数据库中添加一列,因为它是多余的,我不能事先.ToList 一切然后排序,因为数据库中有数百万条记录,这将对性能造成重大影响
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework entity-framework-6