Wednesday, February 6, 2013

Adding Metadata to Generated Classes

If you work with generated classes at all, especially with frameworks like Entity Framework, you've inevitably faced the issue of putting metadata on a generated class. This is easier to do than you might think. For example, let's say you have the following generated class:

1:  public partial class GeneratedClass  
2:  {  
3:     // some code here  
4:  }  

If your generated class is a partial class and you're trying to add class-level metadata, simply create another partial class and add the property as follows:

1:  [MyClassMetadata]  
2:  public partial class GeneratedClass  
3:  {  
4:  }  


On the other hand, if you want to add metadata to a property, you can use the MetadataType attribute as follows. Again, create a second partial class to do this.

1:  [MetadataType(typeof(GeneratedClassValidation))]  
2:  public partial class GeneratedClass()  
3:  {  
4:  }  
5:  public class GeneratedClassValidation  
6:  {  
7:     [MyPropertyAttribute]  
8:     public string MyProperty { get; set; }  
9:  }  

1 comment: