Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to return anonymous types (to make MVC using LINQ possible)

I'd like to implement MVC while using LINQ (specifically, LINQ-to-entities). The way I would do this is have the Controller generate (or call something which generates) the result-set using LINQ, then return that to the View to display the data. The problem is, if I do:

return (from o in myTable select o);

All the columns are read from the database, even the ones (potentially dozens) I don't want. And - more importantly - I can't do something like this:

return (from o in myTable select new { o.column });

because there is no way to make anonymous types type-safe! I know for sure there is no nice, clean way of doing this in 3.5 (this is not clean...), but what about 4.0? Is there anything planned, or even proposed? Without something like duck-typing-for-LINQ, or type-safe anonymous return values (it seems to me the compiler should certainly be capable of that), it appears to be nearly impossible to cleanly separate the Controller from the View.

like image 522
BlueRaja - Danny Pflughoeft Avatar asked Mar 15 '10 21:03

BlueRaja - Danny Pflughoeft


1 Answers

Use a view model layer. Your view has to know what it is going to display. I guess its possible to create a view that just formats a multi-dimensional array of data, but that isn't exactly the best reason to go with an MVC solution. You can however populate a view model with an anonymous object for consumption in your view.

like image 130
Nick Larsen Avatar answered Oct 08 '22 01:10

Nick Larsen