代码之家  ›  专栏  ›  技术社区  ›  JK.

DataAnnotation属性buddy类陌生度-ASP.NETMVC公司

  •  4
  • JK.  · 技术社区  · 14 年前

    public partial class Customer
    {
        [Required]
        [StringLength(20, ErrorMessage = "Customer Number - Please enter no more than 20 characters.")]
        [DisplayName("Customer Number")]
        public virtual string CustomerNumber { get;set; }
    
        [Required]
        [StringLength(10, ErrorMessage = "ACNumber - Please enter no more than 10 characters.")]
        [DisplayName("ACNumber")]
        public virtual string ACNumber{ get;set; }
    }
    

    请注意,“ACNumber”是一个名称不正确的数据库字段,因此autogenerator无法生成正确的显示名称和错误消息,错误消息应为“Account Number”。

    因此,我们手动创建这个buddy类来添加无法自动生成的自定义属性:

    [MetadataType(typeof(CustomerAnnotations))]
    public partial class Customer { }
    
    public class CustomerAnnotations
    {
        [NumberCode] // This line does not work
        public virtual string CustomerNumber { get;set; }
    
        [StringLength(10, ErrorMessage = "Account Number - Please enter no more than 10 characters.")]
        [DisplayName("Account Number")]
        public virtual string ACNumber { get;set; }
    }
    

    [AttributeUsage(AttributeTargets.Property)]
    public class NumberCodeAttribute: RegularExpressionAttribute
    {
        private const string REGX = @"^[0-9-]+$"; 
        public NumberCodeAttribute() : base(REGX) { }
    }
    

    现在,当我加载页面时,DisplayName属性工作正常-它显示来自buddy类而不是生成的类的显示名。

    StringLength属性工作不正常-它显示来自生成类的错误消息(“ACNumber”而不是“Account Number”)。

    但是buddy类中的[NumberCode]属性甚至没有应用于AccountNumber属性:

    foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>())
    {
        // This collection correctly contains all the [Required], [StringLength] attributes
        // BUT does not contain the [NumberCode] attribute
        ApplyValidation(generator, attrib);
    }
    

    为什么 prop.Attributes.OfType<ValidationAttribute>() 集合不包含[NumberCode]属性?NumberCode继承RegularExpressionAttribute,RegularExpressionAttribute继承ValidationAttribute,因此它应该在那里。

    属性属性类型(&L);验证属性>()

    所以我不明白为什么这个特殊的属性在buddy类中不起作用,而buddy类中的其他属性起作用。以及为什么这个属性在自动生成的类中有效,而在buddy中无效。有什么想法吗?

    还有,为什么DisplayName会被buddy覆盖,而StringLength不会?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Josh E    14 年前

        2
  •  1
  •   Alexander    12 年前

    我用VS2008和MVC2重新创建了您的代码,对我来说效果很好。

    推荐文章