Search code examples
entity-frameworkdomain-driven-designautomapperdto

Mapping one DTO to multiple entities


I have the DB model like the following. Here I describe entities I have in the EF model:

   public class Person
   {
      public int Id { get; set; }
      public int AddressId { get; set; }
      public int RoleId { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
   }

   public class Address
   {
      public int Id { get; set; }
      public int CountryId { get;set; }
      public string City { get; set; }
   }

   public class Role
   {
      public int Id { get; set; }
      public string Name { get; set; }
   }

   public class Country
   {
      public int Id { get; set; }
      public string Name { get; set; }
   }

On the front end I have the management interface allowing to edit the user info. So, in each of the grid lines I show the following DTO object:

   public class SystemUser
   {
      public string UserName { get; set; }
      public string Email { get; set; }
      public string City { get; set; }
      public string Country { get; set; }
      public string Role { get; set; }
   }

The main question I have - what is the best way of mapping this back to the entities after edit was performed and I get the DTO back with AutoMapper or something else?

Or am I doing something completely stupid here?

Edit: There is also another challenge I have: I would like to minimize round trips to the DB.


Solution

  • I find AutoMapper a great choice for creating my View Models etc. When saving I find using a Service class with a method such as Save(SystemUser user) is best because then you have room for control over validation and other things that must be done. The mapping code for creating the entities you need to save is hand done, because usually there are a lot more factors involved in the save than in the read. Therefore AutoMapper isn't such a good choice here. I normally write my service class with repositories for the various entities in it's constructor. This is more to allow for unit testing which you haven't mentioned, but would be a good design anyway. If this is the sort of thing you need then I think your on the right track.