views:

28

answers:

1

I'm using EF 4 and I need to find a way to maintain deferred execution and project into another type.

This is my existing code:

AppointmentRepository appointmentRepository = new AppointmentRepository();
var appointmentGridItems = from a in appointmentRepository.ListAppointments()
                           select new AppointmentGridItemViewModel(a);   

This code throws the following runtime exception:

"Only parameterless constructors and initializers are supported in LINQ to Entities."

Is there any other way to shape the linq statement to accomplish what I am after?

Problem Context (if any cares or it has any baring): I need my appointment list serialized as JSON, however serializing the EF ObjectSet results in a circular reference error in the JSON. I the result from my repository has to be deferrable because the grid component I am using (from Telerik's ASP.NET MVC controls) requires it so that data paging can be managed in the DB instead of the View.

Thanks.

A: 
var appointmentGridItems = from a in appointmentRepository.ListAppointments().AsEnumerable()
                           select new AppointmentGridItemViewModel(a);  

...will do it. Yes, this is still deferred. ToArray or ToList would not be deferred; AsEnumerable is.

If you can do something like:

var appointmentGridItems = from a in appointmentRepository.ListAppointments()
                           select new AppointmentGridItemViewModel
                           {
                               Appointment = a
                           };  

Then you can do it completely within L2E. See this post for more examples. L2E supports POCO projections (even in EF 1); it just requires a parameterless constructor.

Craig Stuntz
Thanks for the answer and for correcting my knowledge on Enumerable.