Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 268
Chris McCall Avatar asked Sep 23 '10 20:09

Chris McCall


People also ask

What are all the rules to follow when working with partial class definitions?

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.

What will happen if there is an implementation of partial method without defining partial?

Similar to a partial class, a partial method can be used as a definition in one part while another part can be the implementation. If there is no implementation of the partial method then the method and its calls are removed at compile time. Compiler compiles all parts of a partial method to a single method.

Can partial classes inherit?

Inheritance cannot be applied to partial classes.

Do partial classes have to be in same namespace?

You need to use partial keyword in each part of partial class. The name of each part of partial class should be the same but source file name for each part of partial class can be different. All parts of a partial class should be in the same namespace.


1 Answers

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; }     } } 
like image 70
Jean-François Beauchamp Avatar answered Sep 28 '22 00:09

Jean-François Beauchamp