Linq-to-Entities: Format Date in select query expression

只谈情不闲聊 提交于 2019-11-29 21:06:24

问题


I am trying to get a formatted date string directly from a LINQ-to-Entities query expression.

nonBusinessDays = (from ac in db.AdminCalendar
                   where ac.DateTimeValue >= calendarStartDate && ac.DateTimeValue <= calendarEndDate && ac.IsBusinessDay == false
                   select ac.MonthValue + "/" + ac.DayOfMonth + "/" + ac.FullYear).ToList();

But, I get the folloinw error message: "Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types."

Is there any way to do this besides iterating through the result set? Thanks! Abe


回答1:


I found one workaround:

 nonBusinessDays = (from dt in
                            (from ac in db.AdminCalendar
                             where ac.DateTimeValue >= calendarStartDate && ac.DateTimeValue <= calendarEndDate && ac.IsBusinessDay == false
                             select ac.DateTimeValue).ToList()
                    select string.Format("{0:M/d/yyyy}", dt)).ToList();



回答2:


Try changing your select to use ToString:

nonBusinessDays = (from ac in db.AdminCalendar
                   where ac.DateTimeValue >= calendarStartDate && ac.DateTimeValue <= calendarEndDate && ac.IsBusinessDay == false
                   select ac.DateTimeValue.ToString("MM/dd/yyyy")).ToList();


来源:https://stackoverflow.com/questions/1772753/linq-to-entities-format-date-in-select-query-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!