ViewModel中的DataAnnotations没有覆盖DomainModel属性

时间:2015-04-07 07:44:58

标签: asp.net-mvc-4 viewmodel data-annotations domain-model

如何在视图模型中添加DataAnnotation,继承域模型而不覆盖其属性?

User域模型

public class User{
  public string UserName { get; set; }
  public string Password { get; set; }
}

Register查看模型

public class Register : User{

  [Required]  
  public string Password { get; set; }
}

在这里,有没有办法将DataAnnotation添加到UserNamePassword而不在Register View模型中继承这些属性?

1 个答案:

答案 0 :(得分:0)

您可以创建customrequired属性并将其继承的属性设置为false

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field 
    | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CustomRequiredAttribute : RequiredAttribute
    { 
    }

因此,您的用户域模型如下:

  public class User{

  [CustomRequired]
  public string UserName { get; set; }
  [CustomRequired]
  public string Password { get; set; }
}

现在您的注册模型将如下所示

public class Register : User
{
public string Password{get;set;}
}

现在,子类不会继承必需的属性,如果你挖掘Required属性,你可以找到Inherited布尔属性的定义,如下所示:

  

要点:            获取或设置一个布尔值,指示派生类和覆盖成员是否可以继承指示的属性。

     

返回:            如果属性可以由派生类和覆盖成员继承,则返回true;否则返回false。否则,错误。默认值为true。