views:

296

answers:

2

Hi There, Quick questions really.

I am currently building a site using asp.net MVC and the entity framework. I have a couple of repositories in place which return entities or lists of entities. I am finding that in the majority of my pages I'm having to pull data from a variety of related tables. This is ok so long as I load up the related entities using 'include' in my queries - but is this good practice?

Would it be better to create a custom viewmodel object that contains just the bits of info I need, or is there nothing 'wrong' with pulling an object graph that is perhaps 5 - 6 tables deep just to display what you need to in your view?

Apologies if this question doesn't make too much sense. I may have fundamentally misunderstood how a model should be used here :)

Thanks

+1  A: 

I would suggest reviewing the rendering code in your views and the posting code in your controllers. Are they made overly complex by the approach you are taking? If not you're probably ok to keep things as they are. If the view and controller code would be greatly simplified by introducing a custom view model then consider creating one. Custom view models essentially abstract some of that complexity that is probably getting handled somewhere else at the moment.

Makes sense.Basically, I currently have a situation where I'm pulling various 'tables' from my entity model. Organisations->Buildings->Rooms->Assets. When I display the details of an Asset, I also need to show its room and building information. At the moment I'm just grabbing a sizeable object graph and pulling what I need out in the view. I was just worried that i was bringing too much back from the model. But....it does work.
Sergio
+2  A: 

If your views start doing things like <% foreach (var order in Model.Orders.Any(x => x.Products.Any(p => p.Category == "xx")) %> then you definitely need ViewModel. You can go with ViewData["flattened_orders"] if you prefer magic strings, but I doubt so.

Then, there's a question of presentation attributes needed on your entities, then you need to expose all properties on them so that model binder can work... then you need additional presentation-only information like list of countries...

So, for simple applications, you may skip ViewModel. But for simple applications you can do Response.Write and manual SQL, anyway ;-)

I actually like this post about similar issue. The approach represented there might seem too "academic" at first, but it is from real projects, and the more I do ASP.NET MVC, the more I like it and get closer to it.

queen3
thanks, thats some good advice. I am finding that Im having to navigate through a number entity relationships to get what I need and am starting to think the flatter the data, the better.
Sergio