簡體   English   中英

無法在asp.net vnext類庫中使用必需的屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM