如何将 DataAnnotations 从模型传输到 asp.net 核心中的视图模型?

How to transfer DataAnnotations from model to viewModel in asp.net core?

在我的 ASP.NET 核心项目中,如何在不复制的情况下将 DataAnnotation 属性从 Subject 传输到 SubjectViewModel?

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

你不知道。

视图模型和视图模型的注释不同。

对于视图模型,您需要处理视图数据注释的属性,而在底层模型中,您需要处理持久层的属性,通常与Entity Framework.[=13有关=]

请注意,EF 需要 MaxLength 属性,而 ASP.NET Core MVC 需要 StringLength 属性。

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