.net core数据注解显示名称——继承给viewmodels

.net core data annotation display Name - inherite to viewmodels

我正在尝试创建一个 ASP.NET 应用程序,并在实体 Class 模型中使用 DataAnnotations 以获得更易读的显示名称:

在我的 ApplicationDomain 项目中

public class Car{
    public int Id { get; set; }
    [Display(Name = "Make of Car")]
    public string Make { get; set; }

    [Display(Name = "Year of Purchase")]
    public int PurchaseYear { get; set; }

}

当我将其用作我的视图模型时,一切都按预期显示。

但是当我使用视图模型时,我必须再次添加注释,因为我最初添加到 Car 的显示名称不是 'Inherited' 基于它的视图模型。

在我的 WebMVC 项目中

public class EditCarViewModel{

    [Display(Name = "Make of Car")]
    public string Make { get; set; }

    [Display(Name = "Year of Purchase")]
    public int PurchaseYear { get; set; }
}

创建、索引和任何其他使用视图模型而不是 Car 的视图也是如此 Class。

是否可以将初始实体 class 模型中的注释继承/向上传播到相关的视图模型中,这样我就不必在多个地方执行此操作?

我认为如果我随后尝试添加一个不同的 UI 项目,这将是一个更大的问题。例如除了 WebMVC 之外的桌面应用程序。

如果两者的标签都可以基于 ApplicationDomain 项目中的定义,那将是理想的。

您可以尝试创建一个新的元数据class并将其应用到您的其他元数据。

[MetadataType(typeof(CarModelMetaData))]
public class EditCarViewModel{
    public string Make { get; set; }.
    public int PurchaseYear { get; set; }
}

[MetadataType(typeof(CarModelMetaData))]
public class CreateCarViewModel{
    public string Make { get; set; }
    public int PurchaseYear { get; set; }
}

public class CarModelMetaData{

    [Display(Name = "Make of Car")]
    public string Make { get; set; }

    [Display(Name = "Year of Purchase")]
    public int PurchaseYear { get; set; }
}

无法将注释文本从一个 class 传播到另一个。

但是如果您只想将相同的文本保存在一个地方,您可以创建常量并以这种方式使用它们:

public static class DisplayConstants
{
    public const string Make = "Make of Car";
    public const string PurchaseYear = "Year of Purchase";
}

public class EditCarViewModel{

    [Display(Name = DisplayConstants.Make)]
    public string Make { get; set; }

    [Display(Name = DisplayConstants.PurchaseYear)]
    public int PurchaseYear { get; set; }
}

public class Car
{
    public int Id { get; set; }

    [Display(Name = DisplayConstants.Make)]
    public string Make { get; set; }

    [Display(Name = DisplayConstants.PurchaseYear)]
    public int PurchaseYear { get; set; }
}

请注意,这种方式您可以随意命名EditCarViewModelCar中的属性,不限制一致命名。