Search code examples
c#entity-frameworkdata-annotationsasp.net-dynamic-dataclass-attributes

Is there a way to override order of application of attributes in partial classes?


I have 2 files containing partial classes. A generated on and a manual one. I want to override, cascade, or otherwise specify the order that attributes are applied at compile time in order to change one of the class member attributes.

Generated code:

[Table("dbo.product_variation")]
public partial class ProductVariation
{
    [Key]
    [Column("id")]
    public int Id { get; set; }

    [Required]
    [Column("style_id")]
    public int StyleId { get; set; }

    [Required]
    [Column("name"), StringLength(400)]
    public string Name { get; set; }

    [Column("general_description"), StringLength(2048), UIHint("MultilineText")]
    public string GeneralDescription { get; set; }
}

Manual code:

[MetadataType(typeof(ProductsMetadata))]
public partial class ProductVariation
{
}

public partial class ProductsMetadata
{
    [UIHint("RichText")]
    public string GeneralDescription { get; set; }
}

The real intention here is to override UIHint("MultilineText") with UIHint("RichText"). This is working fine one dev machine, and not on another dev machine, which led me to believe that 1) maybe I shouldn't specify a particular attribute twice, or 2) perhaps there is a way to force the order to override the attribute properly.


Solution

  • That's not possible, the ordering of attributes in the source does not mean anything to the compiler.

    17.2 Attribute specification - MSDN

    The order in which attributes are specified in such a list, and the order in which sections attached to the same program entity are arranged, is not significant

    When you have partial classes and different attributes are used in different source files the compiler just merge them.

    As I stated you cannot make one attribute declaration override another declaration, but what you can do when you're in control of the code which uses the attribute at run time is get all of the attributes applied, apply any ordering you want and only use one of them. But I don't think that's your case.