ASP.NET Core MetaDataType属性不起作用

Met*_*eta 22 c# data-annotations asp.net-core

我在我的域模型类上使用MetaDataType属性.它应该将属性信息从引用的类移动到已设置MetadataType属性的类中.但它没有像宣传的那样做.造成这个问题的原因是什么?

[MetadataType(typeof(ComponentModelMetaData))]
public partial class Component
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Repo> Repos { get; set; }
    public string Description { get; set; }   
}


public class ComponentModelMetaData
{
    [Required(ErrorMessage = "Name is required.")]
    [StringLength(30, MinimumLength = 3, ErrorMessage = "Name length should be more than 3 symbols.")]
    public string Name { get; set; }
    public ICollection<Repo> Repos { get; set; }
    [Required(ErrorMessage = "Description is required.")]
    public string Description { get; set; }        
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*rte 43

ASP.NET核心使用

Microsoft.AspNetCore.Mvc **ModelMetadataType** 
Run Code Online (Sandbox Code Playgroud)

代替

System.ComponentModel.DataAnnotations.**MetadataType** 
Run Code Online (Sandbox Code Playgroud)

资源

尝试将您的属性更改为 [ModelMetadataType(typeof(ComponentModelMetaData))]

  • 最深切的感谢您为.NET Core 1.0找到Microsoft.AspNetCore.Mvc.ModelMetadataTypeAttribute ...不同的名称,不同的命名空间......不难找到.无论如何,这是正确答案,因为部分类Component似乎是模型声明.我更喜欢使用名为相同且与模型位于相同逻辑名称空间的部分类,以将Validate和元数据的注释应用于模型.这样,如果我从数据库重新生成模型,我不会丢失我的编辑. (5认同)
  • 啊。Microsoft.AspNetCore.Mvc 应该仅位于 Web 级别。我讨厌必须将其推入某些业务领域 (4认同)
  • 该解决方案仍然适用于net core 3.0 (3认同)
  • 伙计,这种事情是残酷的,每次我换成像 ASP.NET Core 这样的新技术,我都会在几周内遇到这些障碍。我希望有一种方法可以在某个地方编译它们(即“切换到 ASP.NET Core 时会悄悄发生、浪费你时间、让你感觉不足的 10 件事”) (3认同)