Setting property attributes in incomplete classes

c# class entity-framework partial

Question

I have a class of employees created by Enterprise Framework (EF).

public partial class employee
{
    private string name;
    public string Name
    {
        get{return name;}
        set{ name = value;}
    }
}

Now that I've extended the employee partial class created by EF, I want to add a necessary attribute to the name property to be used for MVC3 validation. By doing this, I won't have to change my code if I refresh the model created by EF.

The assembly and name space are the same for my written partial class.

public partial class employee
{
    // What should I write here to add required attribute in the Name property?
}
1
23
10/18/2011 4:31:09 AM

Accepted Answer

Actually, the only way to do it is in a buddy class, but it is not the best option. Because your object can only store one set of validation characteristics, you should maintain your validation in a custom view model. This is because you often require different validations for various views.

Buddy class illustration

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
  }
}
27
7/25/2011 8:45:01 AM

Popular Answer

I'm not aware that you can; it's simply not practical.

You may want to check to see whether MVC3 has any means of adding characteristics elsewhere (for example, to the type) that correspond to relate to another property.

An alternative would be to include a proxying property:

[ValidationAttributesHere]
public string ValidatedName
{
    get { return Name; }
    set { Name = value; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow