在 LINQ 查询中获取计数



我想在 linq 查询中获取计数,它的工作很好,而无需比较 where 条件下的日期,但在比较日期后它会给出异常。

public static IList GetAllCategoryData()
{
     using (var objEntity = new BlueCouponEntities())
     {
       return (from TBL in objEntity.CategoryMasters.AsEnumerable()
                 let IIT = TBL.CategoryImageTransactions
                 select new
                 {
                 TBL.CategoryID,
                 TBL.CategoryName,
                 CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > DateTime.Now.Date).Count(),
                 }
             ).ToList();
     }
}

错误是:指定的类型成员 ;D ate;在 LINQ to Entities 中不受支持。仅支持初始值设定项、实体成员和实体导航属性。

您必须使用 EntityFunctions.TruncateTime 来获取 DateTime 的 Date 部分

using (var objEntity = new BlueCouponEntities())
{
    return (from TBL in objEntity.CategoryMasters.AsEnumerable()
                 let IIT = TBL.CategoryImageTransactions
                 select new
                 {
                 TBL.CategoryID,
                 TBL.CategoryName,
                 CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > EntityFunctions.TruncateTime(DateTime.Now)).Count(),
                 }
             ).ToList();
}

由于 DateTime.Now 目前是常量,你也可以这样写

 using (var objEntity = new BlueCouponEntities())
 {
     DateTime now = DateTime.Now.Date;
     return (from TBL in objEntity.CategoryMasters.AsEnumerable()
                 let IIT = TBL.CategoryImageTransactions
                 select new
                 {
                 TBL.CategoryID,
                 TBL.CategoryName,
                 CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > now).Count(),
                 }
             ).ToList();   
}

它与 Count() 函数无关。正如例外所说,它的日期时间问题。使用 DbFunctions.TruncateTime(自 EF6 起已弃用EntityFunctions.TruncateTime

public static IList GetAllCategoryData()
{
     using (var objEntity = new BlueCouponEntities())
     {
       return (from TBL in objEntity.CategoryMasters.AsEnumerable()
                 let IIT = TBL.CategoryImageTransactions
                 select new
                 {
                 TBL.CategoryID,
                 TBL.CategoryName,
                 CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && EntityFunctions.TruncateTime(Lg.OfferMaster.EndDate) > EntityFunctions.TruncateTime(DateTime.Now.Date)).Count(),
                 }
             ).ToList();
     }
}

添加以下行:

var today = DateTime.Now.Date;

然后在 linq 查询中使用 today 而不是 DateTime.Now.Date

相关内容

  • 没有找到相关文章

最新更新