I want to reduce the repeated code where I specify the same attributes for an object property used in multiple objects and associated database tables.
I am using property attributes to define how the property should be saved in the database and how it should be titled in UI elements. In my case this property appears in multiple tables/objects and I want it to have the same attributes everywhere. I also want these attributes to get picked up by Entity Framework's code first migrations. It looks like code first migrations loops over the attributes and looks for specific classes like MaxLengthAttribute or classes that inherit from the specific classes. Too bad that Entity Framework doesn't look for interfaces.
I don't want to move this string to a different table because the customers who will use these tables expect them to be directly queried by "CustomerNo".
for example:
[Table("foo")]
public class foo {
…
[Column(TypeName="varchar")]
[MaxLength(15)]
[Display(Name="Customer Identifier")]
public string CustomerNo {get; set;}
…
}
[Table("bar")]
public class bar {
…
[Column(TypeName="varchar")]
[MaxLength(15)]
[Display(Name="Customer Identifier")]
public string CustomerNo {get; set;}
…
}
What I would like to do is make a custom attribute that combines the above attributes into one like [CustomerNoAttribute] (I know I can leave off the suffix "Attribute" it is there to reduce confusion from the class CustomerNo).
There is no multiple inheritance so I cannot just inherit from ColumnAttribute, MaxLengthAttribute, and DisplayAttribute.
Is there a way I can use composition to make this work? e.g.
This code below doesn't work. The new internal attributes are not attached to the properties that I put [CustomerNoAttribute] on.
public CustomerNoAttribute: Attribute {
public CustomerNoAttribute() {
new MaxLengthAttribute(15);
new DisplayAttribute().Name = "Customer Identifier";
new ColumnAttribute().TypeName = "nvarchar";
}
}
Is there another way, to reduce this repetition?
Techniques that use run time addition of attributes wont help because it looks like entity framework's code first migrations look at the compile time attributes only.