【问题标题】:C# adding DataAnnotations to entities from the EntityFrameworkC# 将 DataAnnotations 添加到 EntityFramework 中的实体
【发布时间】:2011-08-04 17:09:12
【问题描述】:

我正在使用 ADO.Net 实体框架。为了处理输入验证,我尝试使用 DataAnnotations,我在 StavkOverflow 和 Google 上四处查看,到处都发现了几乎相同的使用 MetadataType 的示例。但是,我已经尝试了几个小时,但我无法让它工作。由于某种原因,EmployeeMetaData 类的 CustomAttributes 没有应用于Employee 类的相应字段/属性。有谁知道为什么会发生这种情况?是的,我确信属性类型和名称完全匹配。

感谢您的帮助,我已经坚持了几个小时。 提前致谢。

EntityExtentions.cs

[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee:IDataErrorInfo
{
    public string Error { get { return String.Empty; } }
    public string this[string property]
    {
        get
        {
            return EntityHelper.ValidateProperty(this, property);
        }
    }
}

public class EmployeeMetaData
{
    [Required(AllowEmptyStrings=false, ErrorMessage = "A name must be defined for the employee.")]
    [StringLength(50, ErrorMessage = "The name must  be less than 50 characters long.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "A username must be defined for the employee.")]
    [StringLength(20, MinimumLength = 3, ErrorMessage = "The username must be between 3-20 characters long.")]
    public string Username { get; set; }

    [Required(ErrorMessage = "A password must be defined for the employee.")]
    [StringLength(20, MinimumLength = 3, ErrorMessage = "The password must be between 3-20 characters long.")]
    public string Password { get; set; }
}

EntityHelper.cs

public static class EntityHelper
{
    public static string ValidateProperty(object obj, string propertyName)
    {
        PropertyInfo property = obj.GetType().GetProperty(propertyName);
        object value = property.GetValue(obj, null);
        List<string> errors = (from v in property.GetCustomAttributes(true).OfType<ValidationAttribute>() where !v.IsValid(value) select v.ErrorMessage).ToList();

        // I was trying to locate the source of the error
        // when I print out the number of CustomAttributes on the property it only shows
        // two, both of which were defined by the EF Model generator, and not the ones
        // I defined in the EmployeeMetaData class
        // (obj as Employee).Username = String.Join(", ", property.GetCustomAttributes(true));

        return (errors.Count > 0) ? String.Join("\r\n", errors) : null;
    }
}

【问题讨论】:

  • 你想把DataAnnotations直接放在EntityFramework生成的类上吗?我正在使用模型层来分隔数据库模型和应用程序模型。然后我让我的AppBaseEntity 继承IDataErrorInfo 并在我的实体上实现DataValidations。然后我有一个将 EDMX 实体转换为 AppEntities 的工厂。
  • @Philippe Lavoie 是的,这就是我想要做的。这就是我在找到的所有示例中看到的。
  • 对于一个小型应用程序来说,这似乎还不错,但是如果您必须利用实体的更多功能(例如INotifyPropertyChanged、特殊绑定的自定义属性等),您会发现拥有自己的一组实体比使用自动生成的 EDMX 更容易修改(这经常会导致模式更新)。
  • 顺便说一句:你可能应该使用 Environment.NewLine 而不是 "\r\n" 只是说'。
  • 哦,谢谢。没有意识到它有一个常数。

标签: c# wpf entity-framework data-annotations


【解决方案1】:

我使用了这个(网址指向我提出一些想法的有用文章):

// http://www.clariusconsulting.net/blogs/kzu/archive/2010/04/15/234739.aspx
/// <summary>
/// Validator provides helper methods to execute Data annotations validations
/// </summary>
public static class DataValidator
{
    /// <summary>
    /// Checks if whole entity is valid
    /// </summary>
    /// <param name="entity">Validated entity.</param>
    /// <returns>Returns true if entity is valid.</returns>
    public static bool IsValid(object entity)
    {
        AssociateMetadataType(entity);

        var context = new ValidationContext(entity, null, null);
        return Validator.TryValidateObject(entity, context, null, true);
    }

    /// <summary>
    /// Validate whole entity
    /// </summary>
    /// <param name="entity">Validated entity.</param>
    /// <exception cref="ValidationException">The entity is not valid.</exception>
    public static void Validate(object entity)
    {
        AssociateMetadataType(entity);

        var context = new ValidationContext(entity, null, null);
        Validator.ValidateObject(entity, context, true);
    }

    /// <summary>
    /// Validate single property of the entity.
    /// </summary>
    /// <typeparam name="TEntity">Type of entity which contains validated property.</typeparam>
    /// <typeparam name="TProperty">Type of validated property.</typeparam>
    /// <param name="entity">Entity which contains validated property.</param>
    /// <param name="selector">Selector for property being validated.</param>
    /// <exception cref="ValidationException">The value of the property is not valid.</exception>
    public static void ValidateProperty<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> selector) where TEntity : class
    {
        if (selector.Body.NodeType != ExpressionType.MemberAccess)
        {
            throw new InvalidOperationException("Only member access selector is allowed in property validation");
        }

        AssociateMetadataType(entity);

        TProperty value = selector.Compile().Invoke(entity);
        string memberName = ((selector.Body as MemberExpression).Member as PropertyInfo).Name;

        var context = new ValidationContext(entity, null, null);
        context.MemberName = memberName;
        Validator.ValidateProperty(value, context);
    }

    /// <summary>
    /// Validate single property of the entity.
    /// </summary>
    /// <typeparam name="TEntity">Type of entity which contains validated property.</typeparam>
    /// <param name="entity">Entity which contains validated property.</param>
    /// <param name="memberName">Name of the property being validated.</param>
    /// <exception cref="InvalidOperationException">The entity does not contain property with provided name.</exception>
    /// <exception cref="ValidationException">The value of the property is not valid.</exception>
    public static void ValidateProperty<TEntity>(TEntity entity, string memberName) where TEntity : class
    {
        Type entityType = entity.GetType();
        PropertyInfo property = entityType.GetProperty(memberName);

        if (property == null)
        {
            throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, 
                "Entity does not contain property with the name {0}", memberName));
        }

        AssociateMetadataType(entity);

        var value = property.GetValue(entity, null);

        var context = new ValidationContext(entity, null, null);
        context.MemberName = memberName;
        Validator.ValidateProperty(value, context);
    }

    // http://buildstarted.com/2010/09/16/metadatatypeattribute-with-dataannotations-and-unit-testing/
    // Data Annotations defined by MetadataTypeAttribute are not included automatically. These definitions have to be injected.
    private static void AssociateMetadataType(object entity)
    {
        var entityType = entity.GetType();

        foreach(var attribute in entityType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).Cast<MetadataTypeAttribute>())
        {
            TypeDescriptor.AddProviderTransparent(
                new AssociatedMetadataTypeTypeDescriptionProvider(entityType, attribute.MetadataClassType), entityType);
        }
    }
}

这个验证器的最大缺点是:

  • 它的表现就像蜗牛。如果您在单个实体上执行它并不重要,但如果您想与数百、数千或更多实体一起工作,这很重要。
  • 它不支持开箱即用的复杂类型 - 您必须创建特殊属性并在元数据中使用它来验证复杂类型
  • 这是我最后一次使用 DataAnnotations 进行任何业务验证。它们主要用于仅对少数实体进行 UI 验证。

用于验证复杂类型/嵌套对象的属性:

/// <summary>
/// Attribute for validation of nested complex type.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidateComplexTypeAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return DataValidator.IsValid(value);
    }
}

【讨论】:

  • 嘿,谢谢你的帖子。这绝对有帮助。这是我第一次使用 DataAnnotations,实际上我今天才“发现”它们。我可以提高速度,我不仅要在编辑实体时一次验证一个属性,所以我应该没问题。再次感谢。
  • 这是我发现一次验证一个属性的最佳答案。但是,在 Web 服务器的上下文中运行此程序后,服务器在 mscorlib 中崩溃并出现 StackOverflow。我已经删除了这个验证,我不再崩溃了......在查看了TypeDescriptor.AddProviderTransparent 下的代码之后,我认为多次调用它并不重要。但是,在使用此代码时,我确实遇到了异常。
  • 我已将“AddProviderTransparent”调用添加到定义我的元数据的静态构造函数中。这缓解了获取 Stackoverflow 的问题。
【解决方案2】:

尝试验证:

using System.ComponentModel.DataAnnotations;

Validator.TryValidateProperty(propertyValue,
                              new ValidationContext(this, null, null)
                                 { MemberName = propertyName },
                              validationResults);

【讨论】:

  • 谢谢,我想出了一个非常简单的解决方法,效果很好。现在我的问题是如何在抛出ValidationException 时更改错误。例如,该属性是一个整数,但用户输入了一个字符串。我怎样才能改变那个错误。有什么想法吗?
  • 好的,贴在下面。可能没有那么有创意,但它很简单并且似乎有效。使我不必创建和管理所有这些镜像实体。感谢您的所有帮助。
【解决方案3】:

我遇到了同样的问题,并在以下位置找到了我的解决方案 http://blogs.msdn.com/b/davidebb/archive/2009/07/24/using-an-associated-metadata-class-outside-dynamic-data.aspx

关键是调用静态函数TypeDescriptor.AddProvider()

using System.ComponentModel.DataAnnotations;

TypeDescriptor.AddProvider( new AssociatedMetadataTypeTypeDescriptionProvider(typeof(YourEntityClass)), typeof(YourEntityClass));

【讨论】:

    【解决方案4】:

    想出了这个解决方法,因为 CustomAttributes 没有应用于 Employee 类的属性。所以我刚刚得到了实体上的MetaDataType类,找到了对应的属性,并通过ValidationAttributes运行了值。

    public static class EntityHelper
    {
        public static string ValidateProperty(object obj, string propertyName)
        {
            // get the MetadataType attribute on the object class
            Type metadatatype = obj.GetType().GetCustomAttributes(true).OfType<MetadataTypeAttribute>().First().MetadataClassType;
            // get the corresponding property on the MetaDataType class
            PropertyInfo property = metadatatype.GetProperty(propertyName);
            // get the value of the property on the object
            object value = obj.GetType().GetProperty(propertyName).GetValue(obj, null);
            // run the value through the ValidationAttributes on the corresponding property
            List<string> errors = (from v in property.GetCustomAttributes(true).OfType<ValidationAttribute>() where !v.IsValid(value) select v.ErrorMessage).ToList();           
            // return all the errors, or return null if there are none
            return (errors.Count > 0) ? String.Join("\r\n", errors) : null;
        }
    }
    
    [MetadataType(typeof(Employee.MetaData))]
    public partial class Employee:IDataErrorInfo
    {
        private sealed class MetaData
        {
            [Required(AllowEmptyStrings = false, ErrorMessage = "A name must be defined for the employee.")]
            [StringLength(50, MinimumLength = 3, ErrorMessage = "The name must  be between 3-50 characters long.")]
            public object Name { get; set; }
    
            [Required(AllowEmptyStrings = false, ErrorMessage = "A username must be defined for the employee.")]
            [StringLength(20, MinimumLength = 3, ErrorMessage = "The username must be between 3-20 characters long.")]
            public object Username { get; set; }
    
            [Required(AllowEmptyStrings = false, ErrorMessage = "A password must be defined for the employee.")]
            [StringLength(20, MinimumLength = 3, ErrorMessage = "The password must be between 3-20 characters long.")]
            public object Password { get; set; }
        }
    
        public string Error { get { return String.Empty; } }
        public string this[string property] { get { return EntityHelper.ValidateProperty(this, property); } }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      相关资源
      最近更新 更多