Search code examples
c#attributescode-generationpartial-classes

Can I define properties in partial classes, then mark them with attributes in another partial class?


Is there a way I can have a generated code file like so:

public partial class A 
{
    public string a { get; set; }
}

and then in another file:

public partial class A 
{
    [Attribute("etc")]
    public string a { get; set; }
}

So that I can have a class generated from the database and then use a non-generated file to mark it up?


Solution

  • I've seen something like this done in an article by Scott Guthrie (near the end of it) - didn't try it myself, though.
    http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

    [MetadataType(typeof(Person_Validation))]
    public partial class Person
    {
        // Partial class compiled with code produced by VS designer
    }
    
    [Bind(Exclude="ID")]
    public class Person_Validation
    {
        [Required(ErrorMessage = "First Name Required")]
        [StringLength(50, ErrorMessage = "Must be under 50 characters")]
        public string FirstName { get; set; }
    
        [Required(ErrorMessage = "Last Name Required")]
        [StringLength(50, ErrorMessage = "Must be under 50 characters")]
        public string LastName { get; set; }
    
        [Required(ErrorMessage = "Age Required")]
        [Range(0, 120, ErrorMessage = "Age must be between 0 and 120")]
        public int Age { get; set; }
    
        [Required(ErrorMessage = "Email Required")]
        [Email(ErrorMessage = "Not a valid email")]
        public string Email { get; set; }
    }