vendredi 2 octobre 2015

Design pattern: bundle models in controller or in service

We use asp.net mvc with Entity Framework as our ORM.

Our database is really old and was built long time ago. So foreign keys are missing and we can't add it now. We need to bundle different models into ViewModels. We are not sure if we should do the initial model bundling in difference service methods or in the controller.

So my question is what design pattern and practice you think is best. Bundle in controller:

 public class PlayerController : ApiController
 {
     private readonly PlayerService _playerService;
     private readonly ItemService _itemService;

     public PlayerController(PlayerService playerService, ItemService itemService)
     {
         _playerService = playerService;
         _itemService = itemService;
     }


     public UserViewModel Get(int id)
     {
        var user = playerService.GetUser(id);
         var item = itemService.GetItem(id);
         var userViewModel = Mapper.Map<UserViewModel(user);
         userViewModel.item = Mapper.Map<ItemViewModel(item);
         return userViewModel;
     }
 }

Or bundle in the service:

public class PlayerController : ApiController
 {
     private readonly PlayerService _playerService;
     private readonly ItemService _itemService;

     public PlayerController(PlayerService playerService, ItemService itemService)
     {
         _playerService = playerService;
         _itemService = itemService;
     }


     public UserViewModel Get(int id)
     {
        var userWithItem = playerService.GetUserWithItem(id);
        return Mapper.Map<UserViewModel(userWithItem);
     }
 }

The call to getting the item would be done in the "GetUserWithItem" instead, like this:

public User GetUserWithItem(int id)
{
    var user = _dbContext.user.Find(id);
    user.Item = _dbContext.item.Where(x=>x.userId => id);

    return user;
}

Which is the 'correct' way of doing it that would offer most benefits?

Aucun commentaire:

Enregistrer un commentaire