views:

56

answers:

3

Hi,

I'd like to know the best way of converting a list of domain object I retrieve into custom ViewModels in the controller

e.g.

IList<Balls> _balls = _ballsService.GetBalls(searchCriteria);

into

IList<BallViewModels> _balls = _ballsService.GetBalls(searchCriteria);

it doesn't have to be exactly as I've outlined above i.e. it doesn't have to be an IList and if not accessing the service directly and instead go thru some other layer that converts the objects to viewmodels then that is ok too.

thanks

+5  A: 

For simple objects you could just use Linq:

IList<BallViewModel> _balls = _ballsService.GetBalls(searchCriteria)
    .Select(b => new BallsViewModel
                 {
                     ID = b.ID,
                     Name = b.Name,
                     // etc
                 })
    .ToList();

That can get pretty repetitive though, so you may want to give your BallViewModel class a constructor that accepts a Ball and does the work for you.

Another approach is to use a library like AutoMapper to copy the properties (even the nested ones) from your domain object to your view model.

Matt Hamilton
+1  A: 

Probably a bit of Linq, something along the lines of

var ballQuery = from ball in _ballsService.GetBalls(searchCriteria)
                select new BallViewModels
                {
                    Diameter = ball.Diameter,
                    color = ball.Color,
                    ...
                }
IList<BallViewModels> _balls = ballQuery.ToList();

Either that or the question is more complicated than I think...

Murph
sucks being able to give only one answer. thanks
kurasa
There are lots of answers, other ways to do it by hand, creative use of reflection (which is what I assume AutoMapper does) probably some stuff in between - but linq is simple and effective and therefore the obvious answer.
Murph
+1  A: 

I use AutoMapper to do this all the time. It's really flexible and has worked for me without any troubles so far.

First you set up a map like during your app's initialization:

Mapper.CreateMapping<Balls, BallViewModel>();

And whenever you need to map the objects, you would do this:

Mapper.Map<IList<Balls>, IList<BallViewModel>>(_ballsService.GetBalls());

Like I said, it's very flexible and you can modify how the mapping happens for each property using a fluent API.

Ragesh
Nice - shall have to investigate.
Murph