Jaish Mathews
Jaish Mathews

Reputation: 864

Can a 'ViewModel' hold 'DomainModel' type property

In asp.net MVC 4, I have 2 DomainModels

  1. Product
  2. Order

and a related ViewModel

  1. OrderDetailsViewModel

In my "OrderDetailsViewModelMapper" mapper file I am manually mapping these 2 DomainModels to my ViewModel. Mapper file "OrderDetailsViewModelMapper" will call my repository method which will access the DB and return back my 2 DomainModels i.e.Product and Order after mapping them inside repository itself. So mapper just calling repository and getting it's DomainModels. I don't want Automapper. Now I have 2 questions on this scenario.

  1. Whether the above mentioned flow to fill my ViewModel is violating any best practices?
  2. Can I keep 2 properties of type Product & Order inside my "OrderDetailsViewModel" like below and just map those properties only rather than duplicate all properties inside "OrderDetailsViewModel" too and map tem individually?
public class OrderDetailsViewModelMapper
{
public Product Product{ get; set; }
public Order Order{ get; set; }
}

Upvotes: 0

Views: 167

Answers (1)

Wahid Bitar
Wahid Bitar

Reputation: 14074

I think you've some miss.

  • First the mapper class is static class that has some static methods to map objects from one type to another. And the best way is to use the Mapper in your UI not in the Repository. From what I see in your case this should called DTO not Mapper.

  • Second the best for the view model is to hold primitive properties to show at the View NOT to hold navigation properties to the Model.

The best way to get your data from your repository to your ViewModel (List or Single object) is to use Projection against IQueryable<Model> and in this case you don't need to create DTO you just make projection to the suitable ViewModel

e.g.

var list = repository.Query.Select(m=>new ViewModel{
                                      First = m.First.Something,
                                      Second = m.Second.SomethingElse});

Update:

After reading your comment then you need DTO "Data Transfer Object" to be returned from your Repository or you may return your ViewModel directly. It depends about the complexity of your application and who you want to manage that.

Upvotes: 0

Related Questions