Добавление сущности в БД

Имеется следующая сущность:

public class AnimalBreead:BaseEntity
{
    public string Name { get; set; }

    public AnimalType AnimalType { get; set; }
}

public enum AnimalType 
{
    Cat,
    Dog
}

Пытаюсь добавить данную сущность в БД и тут возникают проблемы.

На вход поступает следующий запрос

public class CreateBreeadAnimalRequest
{
    public string Name { get; set; }
    public string Type { get; set; }
}

Он возвращает слудующий ответ

public class CreateBreeadAnimalResponse
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public AnimalType Type { get; set;} 
}

Далее создаю следующий сервис

public class BreeadServices : IBreeadServices
{
    private readonly IMapper _mapper;

    public BreeadServices(IMapper mapper)
    {
        _mapper = mapper;
    }

    public AnimalBreead AddAnimalBreead(CreateBreeadAnimalRequest model)
    {
        if (!Enum.TryParse(model.Type, out AnimalType type))
        {
            throw new Exception("Такого типа животного не существует");
        }

        var breeadAnimal = new CreateBreeadAnimalResponse
        {
            Id = Guid.NewGuid(),
            Name = model.Name,
            Type = type
        };

        return _mapper.Map<AnimalBreead>(breeadAnimal);
    }
}

breeadAnimal формируется корректно

То есть что приходит в CreateBreeadAnimalRequest, то и добавляется в breeadAnimal. Но почему-то в БД добавляется всегда первое значение перечисления, то есть Cat.

Если не обращаться к мапперу, то в БД всё добавляется корректно, то есть сразу формировать сущность AnimalBreead.

Контроллер

[Route("api/v1/[controller]")]
[ApiController]
public class AnimalBreeadController : ControllerBase
{
    private readonly IBreeadRepository _breeadRepository;
    private readonly IBreeadServices _breeadServices;

    public AnimalBreeadController(IBreeadRepository breeadRepository, IBreeadServices breeadServices)
    {
        _breeadRepository = breeadRepository;
        _breeadServices = breeadServices;
    }

    [HttpPost]
    public async Task<IActionResult> CreateAnimalBreeadAsync(CreateBreeadAnimalRequest model)
    {
        try
        {
            var animalBreead = _breeadServices.AddAnimalBreead(model);
            await _breeadRepository.AddAsync(animalBreead);
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }

        return Ok();
    }
}

Маппер

public class AnimalBreeadProfile : Profile
{
    public AnimalBreeadProfile()
    {
        CreateMap<CreateBreeadAnimalResponse, AnimalBreead>();
    }
}

Возможно, с накосячил в классе стартап. Так что приложу его.

        public IConfiguration _configuration { get; }
    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddDbContext<DataContext>(opt => opt.UseNpgsql(_configuration.GetConnectionString("DefaultConnection")));

        services.AddAutoMapper(typeof(AnimalBreeadProfile));

        services.AddScoped<IBreeadServices, BreeadServices>();
        
        services.AddScoped<IBreeadRepository, BreeadRepository>();


        services.AddOpenApiDocument();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseOpenApi();
        app.UseSwaggerUi3(x =>
        {
            x.DocExpansion = "list";
        });

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Ответы (1 шт):

Автор решения: pled

4 дня мучений закончились успехом. В данном случае был неверно настроен мапинг. Поправляем маппинг и радуемся)

public class AnimalBreeadProfile : Profile
{
    public AnimalBreeadProfile()
    {
        CreateMap<CreateBreeadAnimalResponse, AnimalBreead>().ForMember(dest => dest.AnimalType, opt => opt.MapFrom(x => x.Type));
    }
}
→ Ссылка