【问题标题】:Displaying Data Annotation Error Messages in WinForms Using N-Tier Entity Framework使用 N 层实体框架在 WinForms 中显示数据注释错误消息
【发布时间】:2014-06-30 15:23:48
【问题描述】:

请注意,我将 N 层实体框架 (http://ntieref.codeplex.com/) 与 (WCF) SmartClient Winforms 应用程序一起使用。使用数据注释执行客户端验证,我想(模仿 MVC)选择在用户输入值时立即向用户显示数据注释错误消息,和/或选择等待显示所有错误消息用户单击保存按钮时的实体属性(可能使用 Validator.TryValidateObject),但在调用 context.SaveChanges() 之前。

当前,当属性值更改并且用户尝试更改控件焦点时,Entity OnPropertyChanging() 方法会执行,检查属性是否验证(ValidateProperty()),如果验证失败(由于数据注释)抛出异常并且控件不会失去焦点,但不会传递/显示异常/错误消息。

如何获取可用于客户端验证的数据注释错误消息?

@ChristofSenn 你有什么建议吗?

【问题讨论】:

标签: c# entity-framework data-annotations n-tier-architecture client-side-validation


【解决方案1】:

N-Tier Entity Framework 提供多种验证机制:

  1. 在设置属性值时执行早期验证,如果无效则抛出并防止实际设置无效值(默认启用)
  2. IDataErrorInfo 可让您验证属性的当前值(需要 IsValidationEnabled=false 才能在属性上实际设置无效)
  3. ValidateProperty(string propertyName, object value) 允许在不实际尝试将值应用于属性的情况下验证值。

在您的情况下,我认为您需要设置 IsValidationEnabled=false 否则 WinForms DataBinding 无法首先设置无效值,然后使用 IDataErrorInfo 接口不会返回任何验证错误,因为实际上并未设置该值.属性 IsValidationEnabled 在 DataContext、EntitySet 和 Entity 级别上可用。

【讨论】:

    【解决方案2】:

    @ChristofSenn 感谢您的回复。

    1) 为了利用控件/属性的早期验证,我们使用 BindingSource 控件的 BindingComplete 事件来显示验证异常(数据注释错误消息)。

    2) 为了利用 IDataErrorInfo,我们设置 IsValidationEnabled=false 并编写以下代码来获取一串数据注释错误消息。如果有其他方法可以利用 IDataErrorInfo,请告诉我。

    context.EntitySet.IsValidationEnabled = false;
    NTier.Common.Domain.Model.Entity tempEntity = (NTier.Common.Domain.Model.Entity)entityName; string errorMessages = ((System.ComponentModel.IDataErrorInfo) tempEntity).Error; //其中errorMessages包含一串数据注解错误信息。

    3) 我们可以通过使用 entity.ValidateProperty(propertyName, propertyValue) 并捕获异常成功获取数据注释错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      相关资源
      最近更新 更多