views:

356

answers:

3

Let's say I create a query result

var query = from a in tblXYZ join c in tblABC on a.id = b.id select new {a.x, b.x};

What's the best way to pass that into a view? Should I create a new object and copy the query result into it?

+1  A: 

As presented, that will be an anonymous type, which can be accessed (even easier in 4.0 via dynamic) but it is ugly to do so. It also currently suffers from ambiguity over when the data access happens, as the LINQ is deferred, meaning that if you pass that query into the view, you are really doing you data access during the view (and not inside the controller).

I would be tempted to create a class to represent the data (essentially a view-model), and return a list of the entities (not a deferred query).

Marc Gravell
I recommend giving into temptation (at least in this case). :-)
tvanfosson
Just out of curiosity, where should I put this view-model (convention wise)?The view? The controller? A separate file?
jameszhao00
+2  A: 

I think it's almost always the preferred mechanism to create a view-specific model. I would also second @Marc's recommendation to materialize the query in the controller and pass the view to the list. If you have an issue with a query it's much easier to diagnose if the query is executed in the controller rather than the view. The stack trace is actually useful at that point.

tvanfosson
A: 

Put the query in repository. In controller pass the query result to the specified model-view for that view.

Model-View - a specified class for transferring data from controller to the view.

dario-g