views:

31

answers:

1

I have a special stored procedure that returns a List of Distributors from my database. I then iterate through the loop of Distributors and output the results to a web page. However, I need to load the State and the Country for each Distributor. I would rather do this one time, before the loop so that the page is faster. This is my code:

List<Distributor> distQuery =  connection.spDistFindLocal(Lat, Long).ToList<Distributor>();

I know I can do distributor.State.Load(); on each element in my List but I think that is a poor choice. What other options do I have?

+1  A: 

Use a projection:

List<DistributorViewModel> distQuery =  
    (from d in connection.spDistFindLocal(Lat, Long)
     select new DistributorViewModel
     {
         Name = d.Name,
         State = d.State.Name,
         Country = d.Country.Name
     })ToList();

Not only does this load all of the data in one query, but it also omits loading the properties you don't care about for this view.

Craig Stuntz
@Craig - Awesome I didn't even think about the problem in that way! One question, I would need to declare what is in DistributorViewModel right? If so where would I do that? Is there an article somewhere that covers it? This is new territory for me. Thanks!
RandomBen
You can declare a new type anywhere in scope or you can use an anonymous type in some cases. [I wrote an article on this on my blog](http://blogs.teamb.com/craigstuntz/2009/12/31/38500/)
Craig Stuntz