Home > Enterprise >  AutoMapper - Error mapping types for Enums
AutoMapper - Error mapping types for Enums

Time:08-10

I'm developing a web API with ASP.NET Core 6. I am using the library Automapper. When I try to convert my class DTO to my class of Entity, I receive an error, because Automapper fails to recognize and convert enums.

The error:

AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types: CreateRequestUserDto -> User api.DTOs.CreateRequestUserDto -> api.Model.Entity.User

Type Map configuration: CreateRequestUserDto -> User api.DTOs.CreateRequestUserDto -> api.Model.Entity.User

Destination Member: Role

---> AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types: EnumRoles -> Role api.Utilitis.Enum.EnumRoles -> api.Model.Entity.Role

Entity class User.cs:

namespace api.Model.Entity;
public class User
{
    public int Id { get; set; }
    //other attributes
    public virtual Role Role { get; set; }
}

Entity class Role.cs:

using api.Utilitis.Enum;
public class Role
{
    public int Id { get; set; }
    [Column("Name", TypeName = "nvarchar(50)")]
    public EnumRoles Name { get; set; }
    public ICollection<User> Users{ get; set; }
}

DTO class CreateRequestUserDto.cs:

using api.Utilitis.Enum;

namespace api.DTOs;
public class CreateRequestUserDto
{
    //other attributes
    public EnumRoles Role { get; set; }
}

AutoMapperProfile.cs:

public AutoMapperProfile()
{
    CreateMap<User, CreateRequestUserDto>()
        .ForMember(cr => cr.Role, opt => opt.MapFrom(usr => usr.Role.Name)).ReverseMap();
    //other codes
}

Enum.cs:

namespace api.Utilitis.Enum;

public enum EnumRoles { 
    Administrator = 1, 
    Operator = 2 
}

UsersController.cs:

public async Task<ActionResult> Create([FromForm] CreateRequestUserDto request)
{  
    var user = _mapper.Map<User>(request);
    var result = await _userService.CreateUser(user);
    return Ok(new { message = result.Message });
}

ServiceUser.cs:

public async Task<(bool Success, string Message)> CreateUser(User user)
{
    try
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();               

        return (true, "User added");

    } catch(Exception ex)
    {
        return (false, ex.Message);
    }
}

What am I wrong?

CodePudding user response:

You miss out the mapping from EnumRoles to Roles.

Add a mapping from EnumRoles to Roles as below:

CreateMap<EnumRoles, Role>()
    .ConstructUsing((src, dest) => new Role { Id = (int)src });

Sample .NET Fiddle


For inserting a duplicate entry for the Role issue, think that you need to query the Role by Id, then attach it to the user.

ServiceUser.cs

public async Task<(bool Success, string Message)> CreateUser(User user)
{
    try
    {   
        var role = _context.Roles.Single(x => x.Id == user.Role.Id);
        user.Role = role;
 
        _context.Users.Add(user);
        await _context.SaveChangesAsync();               

        return (true, "User added");

    } 
    catch(Exception ex)
    {
        return (false, ex.Message);
    }
}
  • Related