views:

28

answers:

1

This code is a no-go

var errors = (from error in db.ELMAH_Error
         select new
         {
             error.Application,
             error.Host,
             error.Type,
             error.Source,
             error.Message,
             error.User,
             error.StatusCode,
             error.TimeUtc
         }).ToList();

return View(errors);

as it results in a 'requires a model of type IEnumerable' error. The following code of course works fine, but selects all the columns, some of which I'm simply not interested in:

var errors = (from error in db.ELMAH_Error
         select error).ToList();

return View(errors);

I'm brand spanking new to MVC2 + L2E, so maybe I'm just not thinking in the right mindset yet, but this seems counter-intuitive. Is there an easy way to select a limited number of columns, or is this just part of using an ORM?

+1  A: 

This isn't an issue with L2E / L2S, but rather with MVC strongly-typed views.

I'm betting it's not just "requires a model of type IEnumerable", but "a model of type IEnumerable<Something>". If you have a strongly-typed view bound to the type of your errors table, then trying to pass it the anonymous type created by your query (via select new {...}) will cause a type mismatch.

You could either create a new type which contains only the rows that you want, and use that as your view page Model, or you could just do the full select and then limit the columns in your ASP code.

tzaman
It is in fact a strongly typed View - was following the tutorial and forgot about that, so that explains it. If I understand correctly, I create a new strong type for my view (does this go in Models as a standard .cs file?), then instead of referencing IEnumberable<Something>, I point the view to IEnumerable<MyNewType>, and it will be bound to the View's Model?
orlon
Yep, that's pretty much it. Then change your query from `select new {...}` to `select new MyNewType(...)` and you're golden.
tzaman