使用datetimeoffset时Linq到entity framework错误

我得到一个奇怪的错误,我无法解决它。 有人可以帮忙吗?

下面的代码失败了,因为它类似于o.ordered.DateTime.ToShortDateString() (当该部分被注释掉时它起作用)。 o.ordered是一个datetimeoffset 。 它给出的错误如下。 我尝试了一些不同的版本,比如使用datetostring而不是toshortdatestring

 LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression. var BeOrders = from o in BEdb.onlineOrders join s in BEdb.order_Statuses on o.status equals s.ID where o.custCode == pp.AccountID select new DataLayer.OrderStatusItem { city = o.city, customersOrderRef = o.customersOrderRef, date = (o.actualDelivery ?? o.plannedDelivery), date1 = (o.actualCease ?? o.actualCease), number = o.number, ordered = o.ordered.DateTime.ToShortDateString(), postCode = o.postCode, status = s.status, stockCode = o.stockCode, UpdatedByAccount = o.UpdatedByAccount }; 

用于将LINQ代码转换为SQL的数据提供程序无法理解ToShortDateString 。 因此,您不能在发送到数据库的LINQ查询中使用它。 从数据库返回数据后,需要调用此方法:

  var BeOrders = (from o in BEdb.onlineOrders join s in BEdb.order_Statuses on o.status equals s.ID where o.custCode == pp.AccountID select new { city = o.city, customersOrderRef = o.customersOrderRef, date = (o.actualDelivery ?? o.plannedDelivery), date1 = (o.actualCease ?? o.actualCease), number = o.number, ordered = o.ordered, postCode = o.postCode, status = s.status, stockCode = o.stockCode, UpdatedByAccount = o.UpdatedByAccount }).ToList() .Select(x => new DataLayer.OrderStatusItem { city = x.city, customersOrderRef = x.customersOrderRef, date = x.date, date1 = x.date1, number = x.number, ordered = x.ordered.DateTime.ToShortDateString(), postCode = x.postCode, status = x.status, stockCode = x.stockCode, UpdatedByAccount = x.UpdatedByAccount }; 

BTW:还有另一种产生更短代码的解决方案:

  var BeOrders = (from o in BEdb.onlineOrders join s in BEdb.order_Statuses on o.status equals s.ID where o.custCode == pp.AccountID select new { o, s }).ToList() .Select(x => new DataLayer.OrderStatusItem { city = xocity, customersOrderRef = xocustomersOrderRef, date = (xoactualDelivery ?? xoplannedDelivery), date1 = (xoactualCease ?? xoactualCease), number = xonumber, ordered = xoordered.DateTime.ToShortDateString(), postCode = xopostCode, status = xsstatus, stockCode = xostockCode, UpdatedByAccount = xoUpdatedByAccount }; 

这两个版本之间的区别在于第一个版本仅从您需要的数据库中请求那些列,而第二个版本将返回两个表的所有列。

没有简单的解决方案。 在LINQ to Entities您不能使用许多标准方法,如转换。 通常,您只需在查询中执行所有操作,然后调用ToList ,然后您可以使用任何所需的方法。

ToShortDateString的替代方法是使用EntityFunctions.TruncateTime(o.ordered.DateTime)。 这将要求命名空间添加System.Data.Objects。

同样转换为Tolist()将首先将数据加载到内存中,然后在其上应用条件,在应用Tolist()之前,如果它是IQueryable,则将转换请求提供给DB。