【问题标题】:LINQ convert DateTime to stringLINQ 将 DateTime 转换为字符串
【发布时间】:2011-10-16 19:07:45
【问题描述】:
List<Post> list =
(
    from c in db.TitleComments
    join t in db.Titles on c.TitleId equals t.Id
    join u in db.Users on c.UserId equals u.Id
    where t.Id == _titleId && c.Date > time
    orderby c.Date descending
    select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();

上面的代码导致日期到字符串的转换出现异常,PostingDate = c.Date.ToString()。任何想法如何解决这个问题?

异常错误: {"LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且该方法无法转换为存储表达式。"}

【问题讨论】:

  • @BrunoLM,linq 正在尝试使用 sql 将日期转换为字符串,但由于 sql 中没有 ToString() 方法,它无法转换它,我相信这种行为是设计使然。
  • 你能给我们确切的例外吗?我不认为这是 SQL 中抛出的错误。
  • srry 我认为这是一个休眠问题,我的错..
  • 是的。这正是@Joakim 所说的。

标签: asp.net-mvc linq entity-framework entity


【解决方案1】:

linq 正在尝试使用 sql 将日期转换为字符串,但由于 sql 中没有 ToString() 方法,因此无法对其进行转换,因此这种行为是设计使然 - Joakim

也就是说,返回日期本身,并在 SQL 端执行后将其转换为字符串:

(
select new { Username = u.Username,
    PostingDate = c.Date
    [...]
})
.ToList() // runs on SQL and returns to the application
.Select(o =>  // is not generating a SQL, it is running on the app
    new Post { Username = o.Username,
        PostingDate = o.PostingDate.ToString(),
        [...]
    })

【讨论】:

    【解决方案2】:

    您可以通过投影到匿名类型来解决您的问题,然后在数据已经从数据库返回后在稍后的步骤中投影到 Post

    (from ....
     select new { /* stuff */, Date = c.Date })
    .AsEnumerable()
    .Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
    .ToList();
    

    但是,鉴于您有一个名为 PostingDate 的属性,原始来源是一个日期,我建议您修改您的对象以实际将值保留为 @ 987654323@ 而不是字符串。

    【讨论】:

    • 我觉得这就是我要做的,将 PostingDate 设为 DateTime 类型。我想使客户端不必执行日期格式设置,但在这种情况下似乎无济于事。
    【解决方案3】:

    我认为这不能直接完成。

       var list =    
        select new Post { Username = u.Username, PostingDate =  SqlFunctions.StringConvert(c.Date), Data = c.Comment } 
    from 
    (from c in db.TitleComments
        join t in db.Titles on c.TitleId equals t.Id
        join u in db.Users on c.UserId equals u.Id
        where t.Id == _titleId && c.Date > time
        orderby c.Date descending).AsEnumerable()  
        ).ToList();
    

    您也可以尝试使用 EF4:

    List<Post> list =
    (
    from c in db.TitleComments
    join t in db.Titles on c.TitleId equals t.Id
    join u in db.Users on c.UserId equals u.Id
    where t.Id == _titleId && c.Date > time
    orderby c.Date descending
    select new Post { Username = u.Username, PostingDate = SqlFunctions.DateName(c.Date), Data = c.Comment }
    ).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-31
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多