Given this POCO class, which was automatically generated by the EntityFramework T4 template (it cannot and cannot be manually edited in any way):
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; } }
Please note that “ACNumber” is a field with a poorly named database, so the auto-generator cannot generate the correct display name and error message, which should be “Account Number”.
So, we manually create this buddy class to add custom attributes that cannot be automatically generated:
[MetadataType(typeof(CustomerAnnotations))] public partial class Customer { } public class CustomerAnnotations { [NumberCode]
Where [NumberCode] is a simple regex-based attribute that allows only numbers and hyphens to be used:
[AttributeUsage(AttributeTargets.Property)] public class NumberCodeAttribute: RegularExpressionAttribute { private const string REGX = @"^[0-9-]+$"; public NumberCodeAttribute() : base(REGX) { } }
NOW, when I load the page, the DisplayName attribute works correctly - it displays the display name from the buddy class, not the generated class.
The StringLength attribute does not work correctly - it displays an error message from the generated class ("ACNumber" instead of "Account number").
BUT The [NumberCode] attribute in the buddy class does not even apply to the AccountNumber property:
foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>()) {
Why prop.Attributes.OfType<ValidationAttribute>() collection not contain the [NumberCode] attribute? NumberCode inherits RegularExpressionAttribute, which inherits ValidationAttribute, so it should be there.
If you manually move the [NumberCode] attribute into an auto-generated class, it will be included in the prop.Attributes.OfType<ValidationAttribute>() collection.
So I don’t understand why this particular attribute does not work when in the buddy class, when other attributes in the friends class work. And why this attribute works in an auto-generated class, but not in a buddy. Any ideas?
Also, why does DisplayName get the excess from a buddy when StringLength is not working?