I am attempting to modify data via WebAPI using a automapped resource model on my EFCore entity class. I have managed to get GET, GET(by id), DELETE and POST working fine using this method.
Now the problem I face is with an Automapper Serialization and deserialization of 'System.Type' error message I get when trying to do a PUT with this Resource. I managed to narrow this error down my ID field which is a primary key identity field in SQL Server. Omitting this ID in the resource model makes the PUT work.
However, I require the ID field for my other GETS and DELETE so cannot omit it from the resource model.
Here is my Entity:
[Table("BlazorWebApiDemo")]
public partial class BlazorEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("First Name")]
[StringLength(50)]
public string FirstName { get; set; } = string.Empty;
[Column("Last Name")]
[StringLength(50)]
public string LastName { get; set; } = string.Empty;
[StringLength(50)]
public string Address { get; set; } = string.Empty;
}
Here is my API Resource Model:
public class BlazorEntityModel
{
public int Id { get; set; } // Commenting this out makes PUT work.
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
}
Automapper Profile:
public class BlazorEntityProfile : Profile
{
public BlazorEntityProfile()
{
this.CreateMap<BlazorEntity, BlazorEntityModel>()
.ForMember(dest => dest.FirstName, opt => opt.NullSubstitute(""))
.ForMember(dest => dest.LastName, opt => opt.NullSubstitute(""))
.ForMember(dest => dest.Address, opt => opt.NullSubstitute(""))
//.ForMember(src => src.Id, opts => opts.Ignore())
.ReverseMap();
}
}
Controller PUT method:
[HttpPut("{id:int}")]
public async Task<ActionResult<BlazorEntityModel>> UpdateBlazorItem(int id, BlazorEntityModel blazorEntityModel)
{
try
{
var oldBlazorEntity = await blazorRepository.GetBlazorById(id);
if (oldBlazorEntity == null) return NotFound($"LetItem with the ID: {id} not found");
mapper.Map(blazorEntityModel, oldBlazorEntity);
if(await blazorRepository.SaveChangesAsync())
{
return mapper.Map<BlazorEntityModel>(oldBlazorEntity);
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError,
e);
}
return BadRequest(); //Error getting caught here.
}
This is a screenshot of the error I get, in swagger:
Any ideas?