c# - 在 LINQ 中将 datetime2 转换为字符串 ("dd/MM/yyyy")

标签 c# asp.net asp.net-mvc linq type-conversion

我在数据库中有一个 datetime2 列。我正在尝试从数据库中获取它,并且我想在 View 中将其显示为字符串。

我试过了:dt.ToString("dd/MM/yyyy");

但是报错了。

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

我也尝试了 String.Format("{0:y yy yyy yyyy}", dt);,即使这样也会引发错误。

Error

最佳答案

您可以查看此站点:click here

DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

基本上, Entity Framework 不知道如何将 System.Threading.Tasks.Task 的对象转换为 SQL 语句。您可以使用:

SqlFunctions.StringConvert(dt)

或者在使用tostring()之前,使用.tolist():

.ToList().select(p=>new{date=dt.ToString()});

关于c# - 在 LINQ 中将 datetime2 转换为字符串 ("dd/MM/yyyy"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39114188/

相关文章:

c# - 在 WPF 中使用另一个页面上的现有 Canvas

c# - MVC 4 动态操作方法参数

mysql - 如何连接mvc和mysql?

c# - 如何检查 MVC Core 配置文件中的某个部分是否存在?

c# - RequireNonce 为真(默认)但 validationContext.Nonce 为空

c# Appsettings 给出错误 : The name 'ConfigurationManager' does not exist in the current context

c# - 带有奇怪字符的Visual Studio错误

c# - 使用 HttpModule 进行异常处理

c# - 无法使用 S3 TransferutilityUploadRequest 上传文件

c# - EF Core 处理索引冲突的最佳实践