【问题标题】:Convert sql query into linq getting error in converting date将sql查询转换为linq在转换日期时出错
【发布时间】:2013-05-15 07:39:08
【问题描述】:

我的 Sql 查询是:

select count(*),CONVERT(varchar, AddedOn, 101) 
from MemberNotifications where IsActive=1  
group by CONVERT(varchar, AddedOn, 101) 
order by CONVERT(varchar, AddedOn, 101) desc

但我无法得到结果,在下面的尝试中

    List<NotificationCounts> lst =
(from mn in this.MemberNotifications 
 where  mn.UId.Equals(friendId) 
select new NotificationCounts{ NotificationDate = mn.AddedOn.ToString("mm/dd/yyyy") })
.ToList<NotificationCounts>();

我只想获取 mat 字符串中的日期列表,但它给出了一个例外

LINQ to Entities 无法识别方法 'System.String ToString(System.String)' 方法,而且这个方法不能翻译 到商店表达式中。

这个错误有什么解决办法吗?

【问题讨论】:

  • NotificationDateNotificationCounts 类中的类型是什么

标签: c# asp.net sql linq


【解决方案1】:

true... linq 无法将 .ToString 转换为 SQL 指令... 需要获取 mn.AddedOn 的纯值并在数据库获取后对其进行转换。希望对你有帮助

【讨论】:

  • 我已经做到了,但我想按日期使用分组,而 AdditionalOn 是一个日期时间字段,我想只按日期对行进行分组
  • 将数据检索为匿名类型,然后您可以在那里使用 ToString。唯一的问题是检索数据库时。
【解决方案2】:

您不能在那里调用 ToString(),因为没有对 SQL 的转换。 你必须先调用ToList(),然后你可以随意操作内存中的对象:

List<NotificationCounts> lst =
    (from mn in this.MemberNotifications 
     where  mn.UId.Equals(friendId) 
     select 
       new { 
            NotificationDate = mn.AddedOn
       })
    .ToList()
    .Select(n => new NotificationCounts 
                  {
                      NotificationDate  = n.NotificationDate.ToString("mm/dd/yyyy")
                  });

编辑:要按日期分组,请参阅此问题:LINQ to Entities group-by failure using .date 简而言之:使用EntityFunctions.TruncateTime Method

【讨论】:

    【解决方案3】:

    只需将字符串保存到临时变量中,然后在您的表达式中使用它:

    示例:

    var strItem = item.Key.ToString();
    IQueryable<entity> pages = from p in context.pages
                               where  p.Serial == strItem
                               select p;
    

    问题是 ToString() 并没有真正执行,它变成了 MethodGroup,然后被解析并转换为 SQL。由于没有 ToString() 等效项,因此表达式失败。 查看此link 了解更多信息

    【讨论】:

      【解决方案4】:

      使用这个(未测试)

      List<NotificationCounts> lst = (from mn in this.MemberNotifications 
                                      where  mn.UId.Equals(friendId) select mn).ToList()
                                     .Select(mn=>new NotificationCounts
                                     { 
                                        NotificationDate = mn.AddedOn.ToString("mm/dd/yyyy") 
                                     }).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        • 2017-02-23
        • 2020-07-19
        • 1970-01-01
        • 2016-03-08
        相关资源
        最近更新 更多