[ASP.NET 4.0 / EF 4.1]
你好,
我想使用“Linq方法”根据日期字段过滤数据源,但是我遇到了错误:“仅支持原始类型(例如Int32、String和Guid)在此上下文中”。我知道Entity Framework处理日期时有一些限制,但我需要一种优雅的解决方案来处理这个问题。
我的代码如下:
public IList<Order> GetOrders(int? orderId = null, string customerId = null, int? employeeId = null, DateTime? orderDateFrom = null, DateTime? orderDateUntil=null, DateTime? requiredDate = null, DateTime? shippedDate = null)
{
IQueryable<Order> result;
result = from order in ctx.Orders.Include("Order_Details")
select order;
// Apply filters to the base query
if (orderId != null)
result = result.Where(o => o.OrderID.Equals(orderId));
if (!String.IsNullOrEmpty(customerId))
result = result.Where(o => o.CustomerID.ToUpper().Equals(customerId.ToUpper()));
if (employeeId != null)
result = result.Where(o => o.EmployeeID.Equals(employeeId));
if (orderDateFrom != null)
result = result.Where(o => o.OrderDate >= orderDateFrom);
if (orderDateUntil != null)
result = result.Where(o => o.OrderDate <= orderDateUntil);
if (requiredDate != null)
result = result.Where(o => o.RequiredDate == requiredDate);
if (shippedDate != null)
result = result.Where(o => o.ShippedDate == shippedDate);
return result.ToList();
}
当代码执行查询(result.ToList())时,会抛出异常。如果我删除 datetime .Where 子句,它就可以正常工作。
谢谢!
解决方案
我已经将我的代码更改为:
public IList<Order> GetOrders(int? orderId = null, string customerId = null, int? employeeId = null, DateTime? orderDateFrom = null, DateTime? orderDateUntil=null, DateTime? requiredDate = null, DateTime? shippedDate = null)
{
IQueryable<Order> result;
result = from order in ctx.Orders.Include("Order_Details")
select order;
// Apply filters to the base query
if (orderId != null)
result = result.Where(o => o.OrderID.Equals(orderId.Value));
if (!String.IsNullOrEmpty(customerId))
result = result.Where(o => o.CustomerID.ToUpper() == customerId.ToUpper());
if (employeeId != null)
result = result.Where(o => o.EmployeeID == employeeId.Value);
if (orderDateFrom != null)
result = result.Where(o => o.OrderDate >= orderDateFrom.Value);
if (orderDateUntil != null)
result = result.Where(o => o.OrderDate <= orderDateUntil.Value);
if (requiredDate != null)
result = result.Where(o => o.RequiredDate == requiredDate.Value);
if (shippedDate != null)
result = result.Where(o => o.ShippedDate == shippedDate.Value);
return result.ToList();
}
如果有更好的解决方案,请告诉我。
DateTime.Compare(t1, t2)
在 EF linq 查询中能用吗? - FlyingStreudel