实体LINQ不能识别查询中的方法
本文关键字:方法 查询 识别 LINQ 不能 实体 | 更新日期: 2023-09-27 17:54:37
我有以下代码,给了我一个错误,说LINQ到实体不识别方法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到实体正试图翻译我的方法。我不知道如何重写这个查询做所需的结果。
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();
LINQ to Entities不能将自定义方法转换为SQL。你可以把逻辑分成两部分。首先应该从数据库中选择所有需要的字段,并将结果具体化到列表中。第二部分使用SQL无法处理的自定义逻辑处理列表