在linq查询中得到计数

时间:2016-07-08 10:01:00

标签: c# linq lambda

我想在linq查询中计算其工作正常而不比较条件的日期,但在比较日期之后它会给出异常。

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();
     }
}

错误是:指定的类型成员;日期; LINQ to Entities不支持。仅支持初始化程序,实体成员和实体导航属性。

3 个答案:

答案 0 :(得分:2)

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

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();   
}

答案 1 :(得分:1)

它与Count()函数无关。正如例外所说,它 一个DateTime问题。使用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();
     }
}

答案 2 :(得分:1)

添加以下行:

var today = DateTime.Now.Date;

然后使用 今天 而不是 DateTime.Now.Date 进入linq查询。