2015-02-23 64 views
5

更新:當然,我試圖添加using System.ComponentModel.DataAnnotations。它不起作用。無法在asp.net vnext類庫中使用必需屬性

問題:我不能在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

爲什麼倒票?這對我來說似乎是一個合理的問題。 – 2015-02-24 05:07:20

+0

@downvoter,好心地張貼原因也。 – 2015-02-24 06:05:37

回答

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-β1與任何當前版本號。 Visual studio會自動爲你完成它。


爲什麼Microsoft.DataAnnotations工作,而不是System.ComponentModel.Annotations

從一個小調查System.ComponentModel.Annotations包含兩個目標

  • aspnetcore50\System.ComponentModel.Annotations.dll
  • contract\System.ComponentModel.Annotations.dll

aspnetcore50總成是新核心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/

+0

我的問題是爲什麼它與Microsoft.DataAnnotations而不是System.ComponentModel.Annotations一起使用? – 2015-02-24 06:06:39

+0

非常感謝。我會在晚上在家嘗試(我是格林威治標準時間3小時,並沒有VS 2015的工作)。 – colotiline 2015-02-24 06:08:38

+1

好吧,我擴大了答案,解釋爲什麼System.ComponentModel.Annotations不工作,但Microsoft.DataAnnotations呢。 – 2015-02-24 06:50:44