'How do I enforce a method to run when creating an object when I am already using validators from data annotation?
I have a class product and I want to validate the promotion field and change the price based on the value. I am already using data annotation What is the best way to do it following solid principles?
` using System; using System.ComponentModel.DataAnnotations;
namespace RefactoringTest.ProductService.Entities { public class Product : BaseEntity { [DisplayFormat(ConvertEmptyStringToNull = false)] [Required(AllowEmptyStrings = false, ErrorMessage = "ProductName is required.")] public string ProductName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "ProductDescription is required.")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ProductDescription { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 0")]
public int Quantity { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 0")]
public decimal Price { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "BrandName is required.")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string BrandName { get; set; }
public string Promotion { get; set; }
public ProductBrand ProductBrand { get; set; }
public int ProductBrandId { get; set; }
public void CalculatePriceAfterDiscount()
{
switch (Promotion)
{
case "5PERCENTOFF":
Price = Price - Price * 0.05m;
break;
case "10PERCENTOFF":
Price = Price - Price * 0.1m;
break;
case "20PERCENTOFF":
Price = Price - Price * 0.2m;
break;
default:
if (!string.IsNullOrEmpty(Promotion))
throw new ArgumentException("Invalid promotion specified");
break;
}
}
}
}
}`
Also is it ok to have the calculate price method in the class or should be in the service?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
