vendredi 10 mars 2023

Updating an object using efcore

I was creating a UpdateEntityCommand and I wanted to make it flex. If some properties are null then these properties are not modified and they will have the same value before. I've done it with using Reflection. However I am not that sure that this is wise way to do it. These are my entities and codes.

Drink

public class Drink : Product
{
    public string Name { get; set; }
    public int Id {get; set; }
    public double Price { get; set; }
    public string? Explanation { get; set; }
    public double? Calories { get; set; }
    public bool HasStock { get; set; } = true;
    public int? Volume { get; set; }
    public int DrinkCategoryId { get; set; }
    public virtual DrinkCategory DrinkCategory { get; set; }

}

UpdateDrinkDto

public class UpdateDrinkDto
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public double? Price { get; set; }
    public bool? HasStock { get; set; } = true;
    public string? Explanation { get; set; }
    public int? Volume { get; set; }
}

And the methods

public async Task<DrinkDto> Handle(UpdateDrinkCommand request, CancellationToken cancellationToken)
        {
            Drink ?drink = await _drinkRepository.GetAsync(x => x.Id == request.UpdateDrinkDto.Id, x => x.Include(x=>x.DrinkCategory).ThenInclude(x=>x.Menu));
            _drinkBusinessRules.DoesDrinkExists(drink);
            await _businessRules.IsOwnerResponsibleForRestaurant(request.OwnerId, drink.DrinkCategory.Menu.RestaurantId);

            SetProperties(request.UpdateDrinkDto, drink);

            Drink updatedDrink = await _drinkRepository.UpdateAsync(drink);

            DrinkDto response = _mapper.Map<DrinkDto>(updatedDrink);

            return response;





        }

        private void SetProperties(UpdateDrinkDto updateDrinkDto, Drink drink)
        {
            PropertyInfo[] properties = typeof(UpdateDrinkDto).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (updateDrinkDto.GetType().GetProperty(property.Name).GetValue(updateDrinkDto) != null) typeof(Drink).GetProperty(property.Name).SetValue(drink, property.GetValue(updateDrinkDto));
            }
        }

It works as I want it. However I want to learn is there any other way to implement this look. Thank you





Aucun commentaire:

Enregistrer un commentaire