我有以下代码给出了一个错误,说明LINQ to Entities无法识别方法GetShippingHour:
private IEnumerable<OrderDTO> GetAllFixedOrders(DateTime date)
{
var clientSet = _context.Set<Client>();
var orderSubstitutes = _context.Set<OrderSubstitution>()
.Include(o=>o.Order.Client)
.ForCurrentDay(date)
.Select(os => new { os.OrderId, os.FixedOrderId });
var orderList = _context.Set<FixedOrder>()
.Include(fo => fo.Client)
.ForCurrentDay(date)
.Where(fo => !fo.Client.IsInactive)
.ConsideringOrderSubstitution(orderSubstitutes.Select(os => os.FixedOrderId).ToList())
.Join(clientSet
, o => o.ClientId
, c => c.Id
, (o, c) =>
new OrderDTO
{
OrderId = orderSubstitutes.Where(os => os.FixedOrderId == o.Id).Select(os => os.OrderId).FirstOrDefault() ?? 0,
ClientId = c.Id,
ClientName = c.Name,
HasFixedOrders = true,
FixedOrderId = o.Id,
ShippingHour = GetShippingHour(c,date),
HasSpecialProducts = false
}
).ToList();
return orderList;
}
private string GetShippingHour(Client c, DateTime date)
{
var dayOfWeek = date.DayOfWeek.ToString();
string result;
switch (dayOfWeek)
{
case "Sunday":
result = c.ShippingHourSunday ?? c.ShippingHour;
break;
case "Monday":
result = c.ShippingHourMonday ?? c.ShippingHour;
break;
case "Tuesday":
result = c.ShippingHourTuesday ?? c.ShippingHour;
break;
case "Wednesday":
result = c.ShippingHourWednesday ?? c.ShippingHour;
break;
case "Thursday":
result = c.ShippingHourThursday ?? c.ShippingHour;
break;
case "Friday":
result = c.ShippingHourFriday ?? c.ShippingHour;
break;
case "Saturday":
result = c.ShippingHourSaturday ?? c.ShippingHour;
break;
default:
result = c.ShippingHour;
break;
}
return result;
}
问题在于,根据星期几,我需要从Clients表的其他字段中获取ShippingHour的值。问题是LINQ to Entities正试图翻译我的方法。我不知道如何重写此查询以执行所需的结果。
答案 0 :(得分:1)
var orderList = _context.Set<FixedOrder>()
.Include(fo => fo.Client)
.ForCurrentDay(date)
.Where(fo => !fo.Client.IsInactive)
.ConsideringOrderSubstitution(orderSubstitutes.Select(os => os.FixedOrderId).ToList())
.Join(clientSet
, o => o.ClientId
, c => c.Id
, (o, c) =>
new
{
OrderId = orderSubstitutes.Where(os => os.FixedOrderId == o.Id).Select(os => os.OrderId).FirstOrDefault() ?? 0,
Client = c,
HasFixedOrders = true,
FixedOrderId = o.Id,
HasSpecialProducts = false
}
).ToList()
.Select(t=>new OrderDTO {
OrderId = t.OrderId,
ClientId = t.Client.Id,
ClientName = t.Client.Name,
HasFixedOrders = t.HasFixedOrders,
FixedOrderId = t.FixedOrderId,
ShippingHour = GetShippingHour(t.Client,date),
HasSpecialProducts = t.HasSpecialProducts
}).ToList();
答案 1 :(得分:0)
LINQ to Entities无法将自定义方法转换为SQL。您可以将逻辑拆分为2个部分。首先应从数据库中选择所有需要的字段,并将结果具体化为列表。第二部分流程列表,其中包含无法在SQL中处理的自定义逻辑。