猿问

如何向我的POCO(template)类添加验证

因此,我使用了本教程来生成我的poco类,该类将在我的整个应用中使用。.问题是Im不应修改生成的CS文件,因为它们会自动重新生成...如何添加[Required]和像这样的东西??请帮忙


青春有我
浏览 544回答 3
3回答

慕哥9229398

进一步扩大答案。通过使用Microsoft Patterns&Practices企业库5验证模块,除了常规数据注释可用的方法之外,您还可以打开许多验证方法。using Microsoft.Practices.EnterpriseLibrary.Validation;using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;[HasSelfValidation]public partial class Category : ICategory{&nbsp; &nbsp; [SelfValidation]&nbsp; &nbsp; public void Validate(ValidationResults validationResults)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (this.Title === "Credo")&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; validationResults.AddResult(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new ValidationResult(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Category title cannot be a veiled reference to a former cool 2000AD character.",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; null));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; validationResults.AddAllResults(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ValidationFactory&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .CreateValidator<ICategory>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Validate(this));&nbsp; &nbsp; }}using System;using System.ComponentModel.DataAnnotations;using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;public interface ICategory{&nbsp; &nbsp; int Id&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; set;&nbsp; &nbsp; }&nbsp; &nbsp; [Required]&nbsp; &nbsp; [StringLengthValidator(1, 50, MessageTemplate = "Category title should be a maximum of 50 characters in length.")]&nbsp; &nbsp; string Title&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; set;&nbsp; &nbsp; }}

拉莫斯之舞

生成的POCO上的属性是从模型中实体的各个方面派生的。例如,用于[Required]确保该字段为“非空”,并且用于[StringLength(n)]确保数据类型nvarchar(n)通过MaxLength构面。
随时随地看视频慕课网APP
我要回答