首页 文章

无法在asp.net vnext类库中使用required属性

提问于
浏览
5

Update: 当然我试着添加 using System.ComponentModel.DataAnnotations . 它不起作用 .

问题:我不能在asp.net vnext类库项目中使用 Required 属性 .

案件:
1.使用默认设置添加asp.net vnext类库项目 .
2.使用字符串属性 Name 创建类 Human .
3.将 Required 属性添加到 Name .
4.获取编译错误:

Error   CS0246  The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)

下面是我的project.json:

{
    "version": "1.0.0-*",
    "dependencies": {
        "System.ComponentModel.Annotations": ""
    },
    "frameworks": {
        "aspnet50": {
        },
        "aspnetcore50": {
            "dependencies": {
                "System.Runtime": ""
            }
        }
    }
}

我也可以在asp.net vnext中使用 DataAnnotations ,但不能在vnext类库中使用 . 为什么?

1 回答

  • 5

    vNext Web项目依赖于 Microsoft.AspNet.Mvc . 这引入了一个很大的依赖树,数据注释在包 Microsoft.DataAnnotations

    Microsoft.DataAnnotations 添加依赖项以使用数据协定属性 .

    project.json 文件中更改

    "dependencies": {
        "System.ComponentModel.Annotations": ""
    },
    

    "dependencies": {
         "Microsoft.DataAnnotations":  "1.0.0-beta1"
    },
    

    用当前版本号替换1.0.0-beta1 . Visual Studio将为您自动完成它 .


    为什么 Microsoft.DataAnnotations 工作而不是 System.ComponentModel.Annotations

    从一点点调查 System.ComponentModel.Annotations 包含两个目标

    • aspnetcore50\System.ComponentModel.Annotations.dll

    • contract\System.ComponentModel.Annotations.dll

    aspnetcore50 程序集用于新的Core CLR . 它包含 Required 属性,适用于Core CLR .

    contract 程序集包含所有类型,但方法为空 . 它's like a dummy dependency that has to be fulfilled by the framework. This dummy assembly is used on .NET 4.5 which is why your project targeting both .NET 4.5 and the Core CLR can't找到 Required 属性 .

    另一方面, Microsoft.DataAnnotations 包依赖于 System.ComponentModel.Annotations ,但也引用了框架程序集 System.ComponentModel.DataAnnotations ,它实际上提供了在.NET 4.5上运行时的类型

    我觉得这篇文章很有意思 . 它解释了这些 Contract 组件在帖子结尾处的内容 . http://alxandr.me/2014/07/20/the-problems-with-portable-class-libraries-and-the-road-to-solving-them/

相关问题