I've just started working with ASP.NET MVC now that it's in beta. In my code, I'm running a simple LINQ to SQL query to get a list of results and passing that to my view. This sort of thing:
var ords = from o in db.Orders
where o.OrderDate == DateTime.Today
select o;
return View(ords);
However, in my View, I realised that I'd need to access the customer's name for each order. I started using o.Customer.Name
but I'm fairly certain that this is executing a separate query for each order (because of LINQ's lazy loading).
The logical way to cut down the number of queries would be to select the customer name at the same time. Something like:
var ords = from o in db.Orders
from c in db.Customers
where o.OrderDate == DateTime.Today
and o.CustomerID == c.CustomerID
select new { o.OrderID, /* ... */, c.CustomerName };
return View(ords);
Except now my "ords" variable is an IEnumerable of an anonymous type.
Is it possible to declare an ASP.NET MVC View in such a way that it accepts an IEnumerable as its view data where T is defined by what gets passed from the controller, or will I have to define a concrete type to populate from my query?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…