[英]Can't use required attribute in the asp.net vnext class library
更新:当然,我尝试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类库中使用。 为什么?
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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.