我在数据库中有一个 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);
,即使这样也会引发错误。
最佳答案
您可以查看此站点: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/