Data validation with custom attributes (AttributeTargets.Class) on EF buddy classes

后端 未结 1 1409
面向向阳花
面向向阳花 2021-01-06 16:17

I have an Entity Framework generated class with the following properties:

public DateTime LaunchDate;
public DateTime ExpirationDate;

I nee

相关标签:
1条回答
  • 2021-01-06 16:58

    Got it to work by implementing TypeID. I assigned the attribute to the partial class:

        [MetadataType(typeof(PromotionValidation))]
        [PropertyMustBeGreaterThanAttribute("RetailPrice", "DiscountedPrice")]
        [PropertyMustBeGreaterThanAttribute("ExpirationDate", "LaunchDate")]
        [PropertyMustBeGreaterThanAttribute("ClaimDeadline", "ExpirationDate")]
        public partial class Promotion
        {
    ... 
    

    Here is the listing in case anyone needs it:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public class PropertyMustBeGreaterThanAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{1}' must be greater than '{0}'!";
        private readonly object _typeId = new object();
    
        public PropertyMustBeGreaterThanAttribute(string property, string greaterThan)
            : base(_defaultErrorMessage)
        {
            GreaterThan = greaterThan;
            Property = property;
        }
    
        public string Property { get; private set; }
        public string GreaterThan { get; private set; }
    
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                GreaterThan, Property);
        }
    
        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            IComparable greaterThan = properties.Find(GreaterThan, true /* ignoreCase */).GetValue(value) as IComparable;
            IComparable property = properties.Find(Property, true /* ignoreCase */).GetValue(value) as IComparable;
            return greaterThan.CompareTo(property) > 0;
        }
    
        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题