Setting attributes of a property in partial classes

前端 未结 3 1481
鱼传尺愫
鱼传尺愫 2020-12-16 11:01

I have an employee class generated by Entity Framework (EF).

public partial class employee
{
    private string name;
    public string Name
    {
        ge         


        
3条回答
  •  [愿得一人]
    2020-12-16 11:27

    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).

提交回复
热议问题