I have an employee class generated by Entity Framework (EF).
public partial class employee { private string name; public string Name { get{return name;} set{ name = value;} } }
Now I want to put a required attribute in the name property to use in for MVC3 validation in another employee partial class which is written by me in order to extend the one which is generated by EF so that I don't have to rewrite my code if I refresh the model generated by EF.
My written partial class is in the same assembly and name space.
public partial class employee { // What should I write here to add required attribute in the Name property? }
With the help of partial classes, you can separate UI design code and business logic code. For instance, if we develop a web application using the visual studio, some of the source files will get added. These files will have partial keywords.
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.
Partial classes are portions of a class that the compiler can combine to form a complete class. Although you could define two or more partial classes within the same file, the general purpose of a partial class is to allow the splitting of a class definition across multiple files.
Inheritance cannot be applied to partial classes.
It is actually possible only through buddy class but it is not recommended way. You should keep your validation in custom view model because often you need different validations for different views but your entity can keep only single set of validation attributes.
Example of buddy class:
using System.ComponentModel.DataAnnotations; [MetadataType(typeof(EmployeeMetadata))] public partial class Employee { private class EmployeeMetadata { [Required] public object Name; // Type doesn't matter, it is just a marker } }
You can't, as far as I'm aware - it's just not feasible.
You should possibly look to see whether MVC3 has any way of adding attributes elsewhere (e.g. to the type) which relate to another property.
Alternatively, you could add a proxying property:
[ValidationAttributesHere] public string ValidatedName { get { return Name; } set { Name = value; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With