.net - 使用 DataAnnotations 与 WPF 和 Entity Framework 验证数据?

标签 .net wpf entity-framework validation data-annotations

有什么方法可以在 WPF 和 Entity Framework 中使用 DataAnnotations 进行验证吗?

最佳答案

您可以使用 DataAnnotations.Validator 类,如下所述:

http://johan.driessen.se/archive/2009/11/18/testing-dataannotation-based-validation-in-asp.net-mvc.aspx

但是,如果您使用“buddy”类作为元数据,则需要在验证之前注册该事实,如下所述:

http://forums.silverlight.net/forums/p/149264/377212.aspx

TypeDescriptor.AddProviderTransparent(
  new AssociatedMetadataTypeTypeDescriptionProvider(typeof(myEntity), 
    typeof(myEntityMetadataClass)), 
  typeof(myEntity));

List<ValidationResult> results = new List<ValidationResult>();
ValidationContext context = new ValidationContext(myEntity, null, null)
bool valid = Validator.TryValidateObject(myEntity, context, results, true);

[添加以下内容以回应 Shimmy 的评论]

我写了一个通用方法来实现上面的逻辑,以便任何对象都可以调用它:

// If the class to be validated does not have a separate metadata class, pass
// the same type for both typeparams.
public static bool IsValid<T, U>(this T obj, ref Dictionary<string, string> errors)
{
    //If metadata class type has been passed in that's different from the class to be validated, register the association
    if (typeof(T) != typeof(U))
    {
        TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(U)), typeof(T));
    }

    var validationContext = new ValidationContext(obj, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(obj, validationContext, validationResults, true);

    if (validationResults.Count > 0 && errors == null)
        errors = new Dictionary<string, string>(validationResults.Count);

    foreach (var validationResult in validationResults)
    {
        errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage);
    }

    if (validationResults.Count > 0)
        return false;
    else
        return true;
}

在每个需要验证的对象中,我添加对此方法的调用:

[MetadataType(typeof(Employee.Metadata))]
public partial class Employee
{
    private sealed class Metadata
    {
        [DisplayName("Email")]
        [Email(ErrorMessage = "Please enter a valid email address.")]
        public string EmailAddress { get; set; }
    }

    public bool IsValid(ref Dictionary<string, string> errors)
    {
        return this.IsValid<Employee, Metadata>(ref errors);
        //If the Employee class didn't have a buddy class,
        //I'd just pass Employee twice:
        //return this.IsValid<Employee, Employee>(ref errors);
    }
}

关于.net - 使用 DataAnnotations 与 WPF 和 Entity Framework 验证数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1755340/

相关文章:

.net - 如何判断一个对象是否是一个结构体?没有“GetType(Object).IsStructure 函数

wpf - WPF 的 Fluent 设计工具包

entity-framework - 为什么使用 EF 和 AutoFac 时出现错误 : "Cannot access disposed object" in .net core 2?

wpf - 如何设置下一个要写入的文本的RichTextBox字体?

entity-framework - 附加和 EntityState.Detached

c# - 为什么我要在 EF 中进行简单更新时遇到所有障碍?

.net - 我可以在 WinForms 应用程序中使用哪个向导控件?

c# - 将 linq 方法语法转换为查询语法

.net - 是否可以查看在 dll 文件中创建的所有方法和类?

c# - 尝试在 UWP 中初始化 InkCanvas 数组时内存不足,无法继续执行程序