C#C
C#2y ago
Alizer

mapping a dynamic object to an existing object and only map properties that exist in the source obj

I need help with patching an object in ASP Core, on my api i only send a partial data of the object i want to update, i looked into JsonPatchDocument<T> but the syntax is too complicated compared to what my competitors do with their API, what i want here is just for my customers to send a json with the properties and values they want to change and that's it, let's say i have an object like
public class Car
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [MaxLength(Constants.MaxStringLength)]
    public string? Id { get; set; }

    public string? Model { get; set; }

    public string? CompanyName { get; set; }

    // omitted 10+ properties
}


and in my API I only want to update specific properties, so I decided to take a dynamic object in my action

    [HttpPatch]
    [Route("{id}")]
    public async Task<IActionResult> UpdateCarByIdAsync(string id, [FromBody] dynamic car)
    {   
        
        var tenants = await _tenants.UpdateCarFromDynamic(id, car);
        // omitted code


in my update method i have this code

    public async Task<Car?> UpdateCarFromDynamic(string id, dynamic car)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<dynamic, Car>().ForAllMembers(x =>
            {
                x.Condition((src, dest, srcMember) => { return srcMember != null; });
            });
            
        });

        var mapper = _personUserConfiguration.CreateMapper();

        var existingUser =
            await _applicationDbContext.Cars.FirstOrDefaultAsync(x => x.IsActive && x.Id == id);

        mapper.Map(car, existingCar);
        
        // omitted code

now, for some reason existingCar has all properties turned to their default or null values, how should i fix this? is there an alternative library for doing this
Was this page helpful?