在Windows窗体项目上使用DataAnnotations

我最近使用ASP.Net MVC和DataAnnotations,并且正在考虑对Forms项目使用相同的方法,但我不确定如何去做。

我已经设置了我的属性,但是当我单击“保存”时似乎没有检查它们。

更新:我使用了Steve Sanderson的方法 ,它将检查我的类的属性并返回一组错误,如下所示:

try { Business b = new Business(); b.Name = "feds"; b.Description = "DFdsS"; b.CategoryID = 1; b.CountryID = 2; b.EMail = "SSDF"; var errors = DataAnnotationsValidationRunner.GetErrors(b); if (errors.Any()) throw new RulesException(errors); b.Save(); } catch(Exception ex) { } 

您如何看待这种方法?

史蒂夫的例子​​有点陈旧(虽然仍然很好)。 他拥有的DataAnnotationsValidationRunner现在可以被System.ComponentModel.DataAnnotations.Validator类替换,它具有用于validation已使用DataAnnotations属性修饰的属性和对象的静态方法。

这是一个简单的例子。 假设你有一个像下面这样的对象

 using System.ComponentModel.DataAnnotations; public class Contact { [Required(AllowEmptyStrings = false, ErrorMessage = "First name is required")] [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] public string FirstName { get; set; } public string LastName { get; set; } [DataType(DataType.DateTime)] public DateTime Birthday { get; set; } } 

假设我们有一个方法可以创建此类的实例并尝试validation其属性,如下所示

  private void DoSomething() { Contact contact = new Contact { FirstName = "Armin", LastName = "Zia", Birthday = new DateTime(1988, 04, 20) }; ValidationContext context = new ValidationContext(contact, null, null); IList errors = new List(); if (!Validator.TryValidateObject(contact, context, errors,true)) { foreach (ValidationResult result in errors) MessageBox.Show(result.ErrorMessage); } else MessageBox.Show("Validated"); } 

DataAnnotations命名空间与MVC框架无关,因此您可以在不同类型的应用程序中使用它。 上面的代码片段返回true,尝试更新属性值以获取validation错误。

并确保签出MSDN上的引用: DataAnnotations命名空间

如果您使用最新版本的Entity Framework,则可以使用此cmd获取错误列表(如果存在):

 YourDbContext.Entity(YourEntity).GetValidationResult();