The goal of this post is to implement a base class to map and initialize view models using the domain object. This base class should make not only the mapping between the model and the view model but also the validation of the view model using the model annotations.
Each requirement will be implemented in two different base classes, the validation class will inherit from the mapping one as the domain object is needed to validate the view model. It makes sense to split the logic to keep the code cleaner and also to be able to use only the mapping functionality in case that we don’t need the validation.
Result
When this class is implemented we can implement our view models like this:
public class ItemViewModel : BaseEntityMapperViewModel<ItemViewModel, Item>
{
public int Id { get; set; }
public string Name { get; set; }
}
The Model
public class Item
{
[Key]
public int Id { get; set; }
[MaxLength(200)]
[Index(IsUnique = true)]
public string Name { get; set; }
}
Sample of usage:
ViewModel – Model
My WebAPI controllers send and receive to the client a view model instance, when a instance needs to be updated in database it needs to be mapped to the domain first. This is because my domain services know nothing about view models:
// Update item
public void Put([FromBody]ItemViewModel updatedItem)
{
if (!_itemsService.Update(updatedItem.MapToEntity()))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
Model – ViewModel
When a WebAPI need to load a instance from database and send it to the client, it loads a domain instance that needs to be mapped to a view model:
// Read item by id
public ItemViewModel Get(int id)
{
var item = _itemsService.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return ItemViewModel.MapFromEntity(item);
}
Implementation
Continue reading →
Like this:
Like Loading...