我知道这个问题看起来像是重复的,但似乎每个案例都有它自己的解决方案,我找不到这个例外的正确解释:
LINQ to Entities无法识别方法'布尔值 DateReservationOnTheSameWeek(的System.DateTime)'方法和这种方法 无法翻译成商店表达。
我只是想比较两个日期是否在同一个iso周,这里是我的代码:
public class Reservation
{
public DateTime DateReservation { get; set; }
// other methods and properties
public static bool IsOnQuota(Reservation item)
{
using (var ctx = new SchedulingToolContext())
{
float qteSem = ctx.Reservations.Where(k => k.CltNameAlpha == item.CltNameAlpha
&& k.DateReservation.Year == item.DateReservation.Year
&& item.DateReservationOnTheSameWeek(k.DateReservation) // this causes the exception
).Sum(k => k.Qte);
var q = ctx.Quotas.Where(k => k.Id == item.IdQuota).FirstOrDefault();
return q.QteMaxJour >= item.Qte && q.QteMaxSemaine >= qteSem;
}
}
private static int GetIso8601WeekOfYear(DateTime time)
{
DayOfWeek day = System.Globalization.CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
return System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
private bool DateReservationOnTheSameWeek(DateTime date)
{
return GetIso8601WeekOfYear(this.DateReservation) == GetIso8601WeekOfYear(date);
}
}
我无法弄清楚这个谓词失败的原因。 编辑:我无法计算查询中的谓词,因为它取决于k是lambda函数的一部分。
答案 0 :(得分:3)
也许使用SqlFunctions.DatePart和ISO_WEEK会有所帮助
using (var ctx = new SchedulingToolContext())
{
float qteSem = ctx.Reservations.Where(k => k.CltNameAlpha == item.CltNameAlpha
&& k.DateReservation.Year == item.DateReservation.Year
&& SqlFunctions.DatePart("isowk", this.DateReservation) == SqlFunction.DatePart("isowk", k.DateReservation)
).Sum(k => k.Qte);
var q = ctx.Quotas.Where(k => k.Id == item.IdQuota).FirstOrDefault();
return q.QteMaxJour >= item.Qte && q.QteMaxSemaine >= qteSem;
}