I'm currently trying to refactor a method that receives a property name and set it's value:
private async Task < Enrichment > ParseEnrichmentNewDataAsync(int leadId, string property, string newValue) {
var enrichment = await _context.EnrichmentRepository.GetByLeadIdAsync(leadId);
if (enrichment == null) {
enrichment = new Enrichment() {
LeadId = leadId
};
}
Enum.TryParse < PropertyType > (property, out
var enumProperty);
switch (enumProperty) {
case PropertyType.Color:
enrichment.Color = newValue;
break;
case PropertyType.UsedVehicleModel:
enrichment.UsedModel = newValue;
break;
case PropertyType.UsedVehicleYear:
enrichment.UsedYear = newValue;
break;
case PropertyType.UsedVehicleKm:
enrichment.UsedKm = newValue;
break;
case PropertyType.Payment:
enrichment.Payment = Convert.ToInt32(EnumExtension.GetEnumValueFromDescription < PaymentType > (newValue));
break;
case PropertyType.ScheduleDate:
enrichment.ScheduleDate = DateTime.ParseExact(newValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);
break;
case PropertyType.SchedulePeriod:
enrichment.SchedulePeriod = newValue;
break;
case PropertyType.SchedulePhone:
enrichment.SchedulePhone = newValue;
break;
case PropertyType.PurchaseType:
enrichment.PurchaseType = newValue;
break;
case PropertyType.HasOptInNextJeep:
enrichment.HasOptInNextJeep = Convert.ToBoolean(newValue);
break;
}
return enrichment;
}
Using reflection would work for most of the fields, but some values need to be converted before being assigned. Is there a design pattern or a better way to improve this code?
Aucun commentaire:
Enregistrer un commentaire