
我们对实体和成员属性添加验证属性来实施验证规则。WCF RIA Service提供了几个验证属性来执行常用的验证检测,还提供了CustomValIDationAttribute属性来执行自定义的验证检测。
在RIA Service中包含了如下的验证属性:
DataTypeAttribute RangeAttribute RegularExpressionAttribute requiredAttribute StringLengthAttribute
我们在服务端添加验证属性,这些属性会传递给生成的客户端实体。在运行时,这些验证规则会应用到客户输入的数据上。我们必须通过添加元数据类来添加这些验证属性。
添加一个验证属性
为实体类添加一个元数据类,可以参考上一节内容。 对想要验证的实体或成员属性,添加验证属性来执行验证。下面的例子示例如何对一个名字为Address1的成员属性添加验证。?
| 1 2 3 4 5 | [required] [StringLength(60)] public string Addressline1; |
生成解决方案。 在silverlight的应用项目中,打开Generated_Code文件下的代码文件,注意到在客户端代码中也应用了验证属性。
添加自定义验证属性
对实体类添加一个元数据类。 添加一个共享代码文件,以*.shared.cs命名。这个文件将会包含一个自定义验证对象。 添加一个方法来判断是否数据有效。这个方法必须是public和static,还必须返回一个ValIDationResult来表示验证的结果。下面示例是一个有名为IsProductValID方法的ProductValIDator类,这个方法验证一个Product实体。?
| 1 2 3 4 5 6 7 8 9 10 11 12 @H_502_143@ 13 14 15 16 | public class ProductValIDator { public static ValIDationResult IsProductValID(Product productTovalIDate,ValIDationContext context) { if (productTovalIDate.ListPrice < ((decimal).8 * productTovalIDate.Standardcost)) { return new ValIDationResult("ListPrice is below 80 percent of Standardcost."); } else { return ValIDationResult.Success; } @H_502_143@ } } |
对象要验证的实体或成员属性,添加[CustomValIDationAttribute]批注属性,并传递验证对象和执行验证的方法的名字。下面的示例显示了对一个实体应用[CustomValIDation]属性,验证对象的类型是 ProductValIDator,验证方法的名字是 IsProductValID。
?
| 1 2 3 4 5 6 7 8 9 10 11 12 @H_502_143@ 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 @H_905_403@ 42 43 44 45 46 47 48 49 @H_694_419@ 50 51 52 | [CustomValIDation(typeof(RIAServicesExample.Web.SharedCode.ProductValIDator),"IsProductValID")] [MetadataTypeAttribute(typeof(Product.ProductMetadata))] public partial class Product { internal sealed class ProductMetadata { // Metadata classes are not meant to be instantiated. private ProductMetadata() { } @H_502_143@ public string color; public Nullable<DATETIME> discontinuedDate; public decimal ListPrice; public DateTime ModifIEdDate; public string name; public Nullable<INT> ProductcategoryID; public int ProductID; public Nullable<INT> ProductModelID; public string ProductNumber; public GuID rowguID; public Nullable<DATETIME> SellEndDate; public DateTime SellStartDate; [required()] [StringLength(20)] public string Size; @H_905_403@ public decimal Standardcost; public byte[] thumbnailPhoto; public string thumbnailPhotofilename; public Nullable<DECIMAL> Weight; } @H_694_419@ } |
生成解决方案。 在Silverlight客户端,打开Generated_Code文件夹下的文件。注意到在共享代码中CustomValIDationAttribute应用到了实体上。 总结
以上是内存溢出为你收集整理的Silverlight WCF RIA服务(十三)数据 3全部内容,希望文章能够帮你解决Silverlight WCF RIA服务(十三)数据 3所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)