asp.net-mvc – LINQ将DateTime转换为字符串

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – LINQ将DateTime转换为字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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();

上面的代码导致date转换为string,PostingDate = c.Date.ToString().任何想法如何解决这个问题?

异常错误
{“LINQ to Entities无法识别方法’System.String ToString()’方法,并且此方法无法转换为商店表达式.”}

解决方法

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(),[...]
    })
原文链接:https://www.f2er.com/aspnet/247074.html

猜你在找的asp.Net相关文章