Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding DataAnnontations to Generated Partial Classes

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.

like image 448
Naz Avatar asked Aug 05 '09 10:08

Naz


People also ask

Can partial classes inherit?

Inheritance cannot be applied to partial classes.

Can partial classes be in different namespaces?

All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project.

Can partial class have same method name?

Any method, interface, and function declared on a partial class is available for all the other parts. The source file name for each part of the partial class can be different, but each partial class's name must be the same.


2 Answers

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; }
}
like image 125
Adam Cooper Avatar answered Sep 25 '22 22:09

Adam Cooper


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

like image 43
Korayem Avatar answered Sep 21 '22 22:09

Korayem