3

I would like to store DataAnnotations inside a database. How can I retrieve a string representation of a DataAnnotation by reflection (or by other means)?

Example

public class Product
    {
        [DisplayName("Price")]
        [Required]
        [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
        public decimal UnitPrice { get; set; }
    }

Result could be XML or JSON data as long as it is stringified.

W3Max
  • 3,328
  • 5
  • 35
  • 61

2 Answers2

1

this is very similar to retrieve-custom-attribute-parameter-values, i'd use it as a basis for your solution

Community
  • 1
  • 1
jasper
  • 3,424
  • 1
  • 25
  • 46
  • The problem is I don't know the specific type of DataAnnotation so I can't access the properties as in this example (by casting the ValidationAttribute to a specific type). – W3Max Oct 31 '10 at 23:37
1

You'd be better off writing your own validation provider, and then just store the validation rules in your database in a more convenient form. Parsing the strings to try to instantiate the attributes seems like more work than necessary. :)

Sample validation provider: http://bradwilson.typepad.com/blog/2009/10/enterprise-library-validation-example-for-aspnet-mvc-2.html

Brad Wilson
  • 67,914
  • 9
  • 74
  • 83
  • Thank you! Very pleased that you try helping me with this. The problem with the solution you provided is that I need it to work for all kind of DataAnnotations. I use custom attributes to store more than just validation rules. I can’t explain all the concept here but I need it to do exactly what I demonstrated in the example. – W3Max Nov 01 '10 at 00:57
  • You can also write a model metadata provider for non-validation attributes. – Brad Wilson Nov 01 '10 at 01:01