0

problem I have a dto and a main class with id and I made another dto without id. I don't want the id to be displayed on swagger

Service Layer

 public async Task<SuperHeroDto> Create(SuperHeroDto dto) // class with id
    {
        var model = _mapper.Map<SuperHero>(dto); //Main class with id
        _demoAPIDbContext.SuperHeroes.Add(model);
        var saveChange = await _demoAPIDbContext.SaveChangesAsync();
        return _mapper.Map(model, dto);
    }

Question, how can I map the class that has no id?

The attributes of the 3 classes are all the same, only one has no id

 public class CreateSuperHeroDTO
{
    public string Name { get; set; }
    public string FirtstName { get; set; }
    public string LastName { get; set; }
    public string Place { get; set; }
}
sr28
  • 4,728
  • 5
  • 36
  • 67
  • 1
    Does this answer you question: https://stackoverflow.com/a/4988159/580053 ? – Dennis Apr 27 '22 at 08:51
  • Yes, but that's not what I want. The answer is already correct, only I want to pass the separate dto in the service layer, so that at the end the dto returns without an id. Thanks for the alternative –  Apr 27 '22 at 09:04

1 Answers1

0

If you don't want the Id to be displayed just add [JsonIgnore] annotation one line before the property Id.

[JsonIgnore]
public Guid Id { get; set; }
Kvble
  • 286
  • 1
  • 8
  • Isn't it possible to return this, so that it returns this without an id when creating it? and thank you for your quick reply –  Apr 27 '22 at 08:48
  • If you use the nuget package Newtonsoft.Json then adding [JsonIgnore] is gonna make the property Id not visible in the json that swagger is going to get and show after creation – Kvble Apr 27 '22 at 08:53
  • I've tried it and it works. Thanks also for this solution, only I have a sperate dto(CreateSuperHeroDTO) class and I want it at the service layer so that the dto is returned without an id –  Apr 27 '22 at 09:01
  • So you mean you want to return it to controller layer without Id right? – Kvble Apr 27 '22 at 09:08
  • The code contains the method Task Create(SuperHero Dtodto) and I want the separate class without id (CreateSuperHeroDTO) to be returned at the end. –  Apr 27 '22 at 09:12
  • 1
    Either way you can map without the id, with the nuget package AutoMapper you can configure on the startup what classes can be mapped, and if the properties are with the same name then it just works, or else you have to specify which property has to be mapped with another. So it doesn't matter if you have Id or not actually – Kvble Apr 27 '22 at 09:13
  • Thanks, didn't know it was like that –  Sep 16 '22 at 21:16