LINQ的DateTime转换为字符串 [英] LINQ convert DateTime to string
问题描述
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();
上面的code使上日期的皈依串例外,PostingDate = c.Date.ToString()。任何想法如何解决这个问题?
The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?
异常错误:
{LINQ到实体无法识别方法'System.String的ToString()方法,而这种方法不能被翻译成店前pression。}
Exception error: {"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
推荐答案
的 LINQ试图使用SQL日期转换为字符串,但因为是在SQL没有ToString()方法不能将其转换,这种行为是由设计的 - 乔金 -
linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim
在换句话说,返回日期本身以及它在执行SQL上偏后转换为字符串:
In other words, return the date itself and convert it to a string after it executes on SQL side:
(
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(),
[...]
})
这篇关于LINQ的DateTime转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!