Abe
Abe

Reputation: 6516

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

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

Upvotes: 5

Views: 16822

Answers (2)

Geoff
Geoff

Reputation: 9340

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();

Upvotes: 0

Abe
Abe

Reputation: 6516

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();

Upvotes: 9

Related Questions