我的业务层使用了一个名为 DomainObject 的抽象基类,它实现了 IDataErrorInfo 来为 WPF 提供验证绑定。当我调用基类中实现的“错误”属性时,没有发现错误(我的测试产生了两个验证错误)。如果我覆盖派生类中的属性,一切都会按预期工作,并且会发现验证错误。我的猜测是“ValidateFromAttributes”方法中的反射问题......?
我的示例应该返回两个错误。
这是我的代码:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using ValidationResult =
Microsoft.Practices.EnterpriseLibrary.Validation.ValidationResult;
public interface IDomainObject
{
string Name { set; get; }
}
public abstract class DomainObject<T>
: IDataErrorInfo where T : IDomainObject
{
protected DomainObject()
{
}
protected DomainObject(EntityObject entityObject)
{
_entityObject = entityObject;
}
public string this[string columnName]
{
get
{
ValidationResults results = Validation.ValidateFromAttributes(this);
foreach (ValidationResult result in results)
{
if (result.Key == columnName)
{
return result.Message;
}
}
return string.Empty;
}
}
// *** This dosen't work and returns NO errors
public virtual string Error
{
get
{
StringBuilder error = new StringBuilder();
ValidationResults results = Validation.ValidateFromAttributes(this);
foreach (ValidationResult result in results)
{
error.AppendLine(result.Message);
}
return error.ToString();
}
}
private EntityObject _entityObject;
internal EntityObject Entity
{
get { return _entityObject; }
set { _entityObject = value; }
}
}
[HasSelfValidation]
public class BoInvestment : DomainObject<BoInvestment>,
IDomainObject
{
public BoInvestment(){}
internal BoInvestment(EntityObject entityObject) : base(entityObject) {}
[Required]
[StringLengthValidator(7,
MessageTemplate = "Name is too long")]
public string Name { get; set; }
[SelfValidation]
public void Validate(ValidationResults validationResults)
{
if (Name != "Test")
validationResults.AddResult(new ValidationResult(
"Name ist falsch",this,"Name",null,null));
}
// *** This works and returns two errors
//public override string Error
//{
// get
// {
// StringBuilder error = new StringBuilder();
// ValidationResults results = Validation.ValidateFromAttributes(this);
// foreach (ValidationResult result in results)
// {
// error.AppendLine(result.Message);
// }
// return error.ToString();
// }
//}
}
这是单元测试:
[TestMethod]
public void ELValidation()
{
BoInvestment investment = new BoInvestment();
investment.Name = "TestError";
Console.WriteLine(investment.Error);
}