Formatting date in Linq-to-Entities query causes exception

后端 未结 4 1587
遇见更好的自我
遇见更好的自我 2020-12-03 17:57

I have Entity class with datetime filed, I want to select distinct \'mon-yyyy\' format datetime filed value and populate drop down list.

the following code giving me

4条回答
  •  囚心锁ツ
    2020-12-03 18:36

    Here's an alternative:

    .Select( p -> SqlFunctions.StringConvert((double)
                      SqlFunctions.DatePart("m", p.modified)).Trim() + "/" +
                  // SqlFunctions.DateName("mm", p.modified) + "/" + MS ERROR?
                  SqlFunctions.DateName("dd", p.modified) + "/" +
                  SqlFunctions.DateName("yyyy", p.modified)
    

    Apparently DateName("MM", ..) spells out the month name where DatePart("mm", ..) provides a numeric value, thus the StringConvert( ), but this left pads the result with spaces, thus the .Trim().

    Like Anthony Pegram said above, this happens in the database rather than in C# (.AsEnumerable() pulls all data local to C# so make sure you filter data prior to using it.)

    Obviously you'd want to rearrange the output slightly to fit yyyy-MM and use either DatePart for the digit or DateName for the month name.

提交回复
热议问题