Skip to content

Profiles

Leonardo Porro edited this page Feb 12, 2023 · 11 revisions

There are some scenarios where different mapping configuration for the same pair of DTO-Entity may be useful.

For those scenarios, different profiles can be created. A profile is a mapping configuration associated with a key of any type. Then, when calling Map/MapAsync(), the key is passed as an argument and the configuration for the given key it's used.

Configuration

Define some constants to use as a profile key. An enum is a good approach, but it can be any object.

public enum MapperProfiles {
   Update,
   Create
}

Configure the mappings for each profile

services.AddDbContext(opts => {
   opts.UseMapping(mapping =>
     {
         mapping.Default(cfg => {});
  
         mapping.AddProfile(MappingProfiles.Create, cfg =>
         {
            cfg.Type<User>()
               .FromType<UserDTO>()
               .Member(u => u.CreatedDate)
               .FromValue((u, c) => (DateTime?)DateTime.Now);
         });

         mapping.AddProfile(MappingProfiles.Update, cfg =>
         {
            cfg.Type<User>()
               .FromType<UserDTO>()
               .Member(u => u.ModifiedDate)
               .FromValue((u, c) => (DateTime?)DateTime.Now);
         });
      });
});

Use the overload of Map/MapAsync() that takes the key as an argument

UserDTO dto = new UserDTO { Id = 1, Name = "user name" };
User newUser = dbContext.Map<User>(MappingProfiles.Create, dto);
UserDTO dto = new UserDTO { Id = 1, Name = "user name" };
User newUser = dbContext.Map<User>(MappingProfiles.Update, dto);

IMPORTANT: If no key is provided, the default configuration is used, so that, in this example, no special mapping would be applied.