【发布时间】: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