Setting attributes of a property in partial classes

蓝咒 提交于 2019-11-29 02:59:13

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; }
}
jahu

Another way to do this is:

private class EmployeeMetadata
{
    //the type HAS to match what your have in your Employee class
    [Required]
    public string Name { get; set; }
}

public partial class Employee : EmployeeMetadata
{
}

At least this worked with Linq to SQL. However I had trouble accessing the attributes through GetCustomAttributes (even using System.Attribute.GetCustomAttributes didn't seem to help). Nonetheless MVC did respect those attributes. Additionally this will not work with inheriting from interfaces. Passing attributes from interface will only work using MetadataType class attribute (see answer by Ladislav Mrnka).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!