I’m starting to use AutoMapper and some doubts arose.
Where is the correct way to map a dto into a domain model?
I’m doing this:
DTO:
public class PersonInsert
{
[Required]
public string Name { get; set; }
public string LastName { get; set; }
}
Action:
[HttpPost]
public ActionResult Insert(PersonInsert personInsert)
{
if (ModelState.IsValid)
{
new PersonService().Insert(personInsert);
return RedirectToAction("Insert");
}
return View("Insert");
}
Service:
public class PersonService
{
public int Insert(PersonInsert personInsert)
{
var person = Mapper.Map<PersonInsert, Person>(personInsert);
return new PersonRepository().Insert(person);
}
}
Repository:
public class PersonRepository
{
internal int Insert(Person person)
{
_db.Person.Add(person);
_db.SaveChanges();
return person.Id;
}
}
So, is this correct? should my service knows about domain? or should I make the bind in repository only? is correct to use [Required] in DTO?
I personally don’t see anything wrong with having your service do the mapping
No, DTOs should have no business logic whatsoever. They should be used purely for transmitting data across different tiers/layers of your application.
DataAnnotations are typically used on
ViewModelsfor client/server side validation, therefore, I would add another separation into your model and introduce aViewModelfor yourInsertaction e.g.Action:
Service:
It may seem overkill in this scenario (considering the only difference is the
[Required]attribute). However, in a typical MVC application you would want to ensure a clean separation between yourViewModels and your business models.