首页 > 解决方案 > 覆盖 .NET Core 中的默认 Required ErrorMessage 属性

问题描述

我已经使用带有 DataAnnotations 集的 EF 生成了我的 DbContext,并希望使用 ModelMetadataType 覆盖所需的 ErrorMessage 属性

例如

生成的类

public partial class ControlType
{
    public ControlType()
    {
        Rule = new HashSet<Rule>();
    }

    [Key]
    public int ControlTypeId { get; set; }
    [Required]
    [StringLength(200)]
    public string Name { get; set; }

    [InverseProperty("ControlType")]
    public virtual ICollection<Rule> Rule { get; set; }
}

我的扩展类

[ModelMetadataType(typeof(ControlTypeMeta))]
public partial class ControlType
{
}

public class ControlTypeMeta
{
    [Display(Name = "Id")]
    public int ControlTypeId { get; set; }

    [Display(Name = "Control type")]
    [Required(ErrorMessage = "'{0}' is required")]
    public string Name { get; set; }
}

有了上面的内容,我期望将所需的错误消息输出为“需要'控制类型'”,但我得到默认的“需要控制类型字段”

截屏

有谁知道我可以如何覆盖消息(不创建视图模型)

标签: entity-framework.net-core

解决方案


推荐阅读