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

Chris McCall picture Chris McCall · Sep 23, 2010 · Viewed 35k times · Source

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?

Answer

Jean-François Beauchamp picture Jean-François Beauchamp · Oct 19, 2013

Here is the solution I have been using for such cases. It is useful when you have auto-generated classes that you want to decorate with attributes. Let's say this is the auto-generated class:

public partial class UserProfile
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

And let's say, I would like to add an attribute to specify that UserId is the key. I would then create a partial class in another file like this:

[Table("UserProfile")]
[MetadataType(typeof(UserProfileMetadata))]
public partial class UserProfile
{
    internal sealed class UserProfileMetadata
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
    }
}