In my ASP.NET Core project, How can I transfer DataAnnotation attributes from Subject to SubjectViewModel without duplicating them?
public class Subject
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is Required")]
[MaxLength(200, ErrorMessage = "Name MaxLength is 200")]
public string Name { get; set; }
public string Description { get; set; }
}
public class SubjectViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
You don't.
The annotations for the view model and the view model are different.
For the view model you want the attributes that deal with data annotation of the the view, while in the underlying model you want attributes that deal with the persistence layer, usually related to Entity Framework.
Note that EF expects the MaxLength
attribute, while ASP.NET Core MVC expects the StringLength
attribute.
[Table("Subjects")]
public class Subject
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(200]
public string Name { get; set; }
public string Description { get; set; }
[NotMapped]
public string Foo { get; set; }
}
public class SubjectViewModel
{
public int Id { get; set; }
[Display(Name = "Full name")]
[Required(ErrorMessage = "Name is required")]
[StringLength(200, ErrorMessage = "Name MaxLength is 200")]
public string Name { get; set; }
[AllowHtml]
[DataType(DataType.Multiline)]
public string Description { get; set; }
}