使用带有DataAnnotations的可移植类库共享程序集

Max*_*ich 9 c# asp.net-mvc data-annotations portable-class-library windows-phone-8

我创建了一个可移植的类库DataContracts,其中包含我的项目Messages和Views.标准的东西像GetStockItemByIDRequest和StockView包含在里面.

问题在于我试图DataAnnotations通过使用System.ComponentModel.DataAnnotations我的一些东西来添加Views.

[DataContract]
public class StockView
{
    [Required]
    [DataMember]
    public Guid StockID { get; set; }

    [Required]
    [DataMember]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我可以成功添加System.ComponentModel.DataAnnotations到我的可移植类库项目,并可以在我的Windows Phone 8应用程序中成功引用它,甚至可以在我的Windows Phone应用程序中创建我的视图的新实例StockView View = new StockView();但是如果我尝试使用其中任何一个Newtonsoft.Json或System.Net.Http.HttpClient通过执行某些操作喜欢

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://myservice.com");
T result = await response.Content.ReadAsAsync<T>();
Run Code Online (Sandbox Code Playgroud)

要么

T result = await Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>("{}");
Run Code Online (Sandbox Code Playgroud)

即:涉及反序列化的地方......

我面临着错误Could not load file or assembly 'System.ComponentModel.DataAnnotations, Version=2.0.5.0'.我假设是因为它似乎不System.ComponentModel.DataAnnotations 支持Windows Phone 8(但为什么我可以将它添加为我的PCL的参考?).

所以我的问题是,为什么在我直接创建这些类的新实例时不会调用此错误,其次如何解决此问题?

Dan*_*ted 5

遗憾的是,DataAnnotations目前不具备可移植性.虽然有点复杂,但您可以通过在PCL中编写自己的DataAnnotation属性来解决这个问题,并为.NET Framework项目创建一个具有相同名称的程序集,并将属性转换为"真实"版本.有关详细信息,请参阅此答案.


Max*_*ich 5

好吧,事实证明我原来的假设是完全错误的.您绝对可以System.ComponentModel.DataAnnotations从Windows Phone 8项目引用命名空间.

基本上它归结为反直观地引用可以位于的dll的silverlight版本 C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\System.ComponentModel.DataAnnotations.dll

有关如何构建可移植类库的更多信息,我建议参考本文.