views:

198

answers:

1

I'm using LINQ to SQL (SQL Server) within ASP.Net MVC. My page needs to display all Regions and all Offices within each Region (nested). Offices belong to a Suburb, which in turn, belong to a Region. I.e. Within each Region, I need to grab the Offices which exist inside Suburbs which belong to the current Region in the loop.

(Pseudo code)

    foreach(Region currentRegion in Regions)  
    {  
        Display Region's Heading  
        foreach(Office currentOffice in ALL OFFICES WHICH BELONG TO SUBURBS WHICH BELONG TO THIS REGION)  
        {  
             Display Office Name  
        }  
    }  

What is the cleanest, MVC paradigm way to achieve this with LINQ to SQL?
(I'm a massive SQL fan, but I'm using LINQ to SQL for this project).

I don't want to have to write 5 helper classes just to do such a simple thing. I am not looking for a "perfect world OO overkill" solution, clean, minimalist and simple is best.

I'd ideally like to assemble all the data in the Controller so that I don't end up with some chaotic view that overlaps with Controller responsibility etc.

Many thanks..

A: 

In your case,

  • i would create view model classes RegionModel, SuburbModel, OfficeModel.
  • Using AutoMapper, i would map Region to RegionModel and pass it to view
  • View would look like this (Spark) =>

    <viewdata model="RegionModel region" />
    <for each="var suburb in region.Suburbs">
        <span each="var office in suburb.Offices">${office.Name}</span>
    </for>        
    

That's an answer to question 'how to pass nested data to view in asp.net-mvc?'. Thing is - your Model does not fit to this yet (Region class is not directly bound with Suburbs, Suburbs with Offices).

So - you need to make sure your Region contains Suburbs and Suburb contains Offices. I'm not sure about L2S but in nhibernate that would be easy - collections would be mapped as is and by default - kept lazy loaded. RegionController would be responsible for using RegionRepository properly and RegionRepository should provide possibility to eager load suburbs & offices on demand.

Arnis L.
Hi Arnis! Thx for your answer. While I'm sure Spark and AutoMapper are fantastic add-ons, I am interested in knowing how this can be done with pure/raw ASP.Net MVC at this stage. I want to get my knowledge in this area spot on first before I go learning even more classes/add-ons etc. I've found that the more add-ons you go tacking onto your solution, can often end up with increased maintenance overheads in 2-3 years time when part of your solution gets upgraded and all of a sudden some of the add-ons may then be unsupported or no longer compatible etc.
Aaron
Nothing much would change - syntax of view would be a bit more verbose and mapping would be done creating view models through constructors or object initializers.
Arnis L.