[英]Is there a better way to implement model validation with Entity Framework+IDataErrorInfo than this?
Currently, I have this : 目前,我有这个:
This works, however : is there anyway I can move the generic code to some other class? 然而,这是有效的:无论如何我可以将通用代码移动到其他类吗? What's the best approach?
什么是最好的方法? We (before moving to Entity Framework) used to have an "Entity" class and a Poco.
我们(在迁移到实体框架之前)曾经有过一个“实体”类和一个Poco。 This entity class extend from some base class where interfaces where implemented like IDataErrorInfo .
此实体类从某些基类扩展,其中实现的接口类似于IDataErrorInfo。 Because the other part of the partial class already extends from EntityObject, I cannot use this approach, but I feel stupid writing every partial class again 80% the same code.
因为部分类的其他部分已经从EntityObject扩展,我不能使用这种方法,但是我觉得愚蠢地再写80%相同代码的每个部分类。 The only "real" difference would be the logic of the Validate method.
唯一的“真正”差异是Validate方法的逻辑。
public partial class Customer : IDataErrorInfo, ICustomer
{
private readonly IDictionary<string, string> _errors = new Dictionary<string, string>();
public Customer()
{
base.
PropertyChanged += Model_PropertyChanged;
}
private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Validate();
}
private void Validate()
{
if (Name != null && Name.Equals("Banana"))
{
this[GetPropertyName(() => Name)] = "Some really nice error here";
}
}
#region "IDataErrorInfo"
public virtual string this[string columnName]
{
get
{
if (_errors.ContainsKey(columnName))
{
return _errors[columnName];
}
return null;
}
protected set
{
if (value == null && _errors.ContainsKey(columnName))
{
_errors.Remove(columnName);
}
else
{
if (_errors.ContainsKey(columnName))
_errors[columnName] = value;
else
_errors.Add(columnName, value);
}
}
}
public virtual string Error
{
get
{
if (_errors.Values.Count > 0)
{
return _errors.Values.First();
}
return null;
}
}
#endregion
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
}
您可以使用IValidatableobject请参阅http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.