无法在asp.net vnext类库中使用必需的属性

马克·吐温

更新:当然,我尝试添加using System.ComponentModel.DataAnnotations没用

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

案例:
1.使用默认设置添加asp.net vnext类库项目。
2.Human使用string属性创建类Name
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": ""
            }
        }
    }
}

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

杰瑞德·凯尔斯(Jared Kells)

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组件包含了所有的类型,但这些方法都是空的。就像框架必须满足的虚拟依赖关系一样。该虚拟程序集在.NET 4.5上使用,这就是为什么同时针对.NET 4.5和Core CLR的项目找不到该Required属性的原因。

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

我发现这篇文章很有趣。它解释了这些合同组装在职位后期的含义。http://alxandr.me/2014/07/20/the-problems-with-portable-class-libraries-and-the-road-to-solving-them/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章