views:

1792

answers:

3

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

+3  A: 

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();
AbeP
The problem you're having is that its attempting to translate ToString into valid SQL to execute on the server - and which its then failing to do. The nested queries mean that you're separating the .ToString which can't be done from the query that can and hence it works
Murph
Thanks!It makes sense now; LINQ is trying to map the function to a SQL function, which does not exist.My workaround was to first get the data into a list and process the list from there.
AbeP
A: 

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();
Geoff
Unfortunately, you can't run the ToString method either; here's the exception I got:LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
AbeP
A: 

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

Hrushikesh