Adding DataAnnontations to Generated Partial Classes
Asked Answered
B

3

7

I have a Subsonic3 Active Record generated partial User class which I've extended on with some methods in a separate partial class.

I would like to know if it is possible to add Data Annotations to the member properties on one partial class where it's declared on the other Subsonic Generated one I tried this.

public partial class User
{
    [DataType(DataType.EmailAddress, ErrorMessage = "Please enter an email address")]
    public string Email { get; set; }

    ...
}

That examples gives the "Member is already defined" error.

I think I might have seen an example a while ago of what I'm trying to do with Dynamic Data and Linq2Sql.

Bream answered 5/8, 2009 at 10:51 Comment(0)
F
11

What you will need to do is create a 'buddy class' and apply the Data Annotations to that class:

[MetadataType(typeof(UserValidation))]
public partial class User 
{
  ...
}

public class UserValidation
{
  [DataType(DataType.EmailAddress, ErrorMessage = "Please enter an email address")]
  public string Email { get; set; }
}
Fester answered 5/8, 2009 at 11:55 Comment(0)
V
1

You should create a buddy class as explained here by Scott Guthrie http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Vanquish answered 8/1, 2011 at 0:46 Comment(1)
Also this explains a nifty way of to let subsonic even create that buddy class for you subsonicproject.com/docs/User_talk:Minus4Vanquish
Q
0

This won't directly answer your question, but I had the same problem, and rather than using DataAnnotations, I've been using the FluentValidation framework {0} with great success so far. It works nicely because it provides much of the same functionality, but doesn't apply validation by using attributes on members of the class. Validation happens in a completely separate class that acts on the class being validated (i.e. UserValidator).

{0}: http://fluentvalidation.codeplex.com/

Quiet answered 6/8, 2009 at 1:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.