So I have an almost 1:1 ratio of views to view models and things seem to be going well. If I understand their purpose correctly it seems that view models should
- "Strip down" Entity models so that only relevant properties are passed to the presentation layer
- Add additional information needed for presentation such as a list of state abbreviations or contact types when creating, say, an address.
In trying to keep with those principles I've sort of hit a bit of a wall with my Reports controller. Various reports that are generated for a customer require access to about 30 or so different properties. As such, my view model ends up looking very similar to my Entity model.
Of course the easiest solution is to just pass the Entity model to the view so that I'll have access to all properties, however I also need to be able to generate reports for blank or "incomplete" customers. This causes problems will null reference exceptions when trying to access navigation properties on my Entity models.
So I can either use a null check on just about every field within the view, which doesn't seem too appealing... OR I could implement a view model to avoid the null reference exceptions. The problem is that I'd end up with a view model that looked like this:
var customer = customersRepository.GetCustomer(id);
var viewModel = new CustomersViewModel()
{
FirstName = customer.FirstName,
LastName = customer.LastName,
Address = customer.MailingAddress.Address,
City = customer.MailingAddress.City,
// and on and on for about 30 different properties
};
return View(viewModel);
Typing all those properties out is one of those things that just feels wrong. Am I missing a more elegant solution to this problem?