如何使用 VAB / 实体框架验证单个属性?
我正在使用实体框架,所有实体都继承自 BaseObject:
public class BaseObject : IDataErrorInfo
{
private string _validationMessage;
public BaseObject()
{
_validationMessage = string.Empty;
}
public void Validate()
{
Validator validator = ValidationFactory.CreateValidator(GetType());
var validationResults = validator.Validate(this);
if (validationResults.Count > 0)
{
StringBuilder message = new StringBuilder();
foreach (var validationResult in validationResults)
{
message.Append(validationResult.Message);
message.Append(Environment.NewLine);
}
_validationMessage = message.ToString();
//throw new ValidationException(message.ToString());
}
}
public string Error
{
get
{
_validationMessage = string.Empty;
this.Validate();
return _validationMessage;
}
}
public string this[string columnName]
{
get
{
_validationMessage = string.Empty;
this.Validate();
return _validationMessage;
}
}
}
BaseObjects 实现 IDataErrorInfo 接口,因此我可以将 ErrorProvider 与绑定源结合使用。这段代码的问题在于,当一个属性无效时,所有其他属性也无效。所以我的问题是,我该如何解决这个问题?我正在使用验证应用程序块,但我不知道如何验证单个属性。
I'm using Entity Framework and all the entities inherits from BaseObject:
public class BaseObject : IDataErrorInfo
{
private string _validationMessage;
public BaseObject()
{
_validationMessage = string.Empty;
}
public void Validate()
{
Validator validator = ValidationFactory.CreateValidator(GetType());
var validationResults = validator.Validate(this);
if (validationResults.Count > 0)
{
StringBuilder message = new StringBuilder();
foreach (var validationResult in validationResults)
{
message.Append(validationResult.Message);
message.Append(Environment.NewLine);
}
_validationMessage = message.ToString();
//throw new ValidationException(message.ToString());
}
}
public string Error
{
get
{
_validationMessage = string.Empty;
this.Validate();
return _validationMessage;
}
}
public string this[string columnName]
{
get
{
_validationMessage = string.Empty;
this.Validate();
return _validationMessage;
}
}
}
BaseObjects implements the IDataErrorInfo interface so I can use the ErrorProvider in combination with a bindingsource. The problem with this code is that when one property is invalid, all the other properties are invalid too. So my question is, how can I solve this? I am using the Validation Application Block and I don't know how I can validate a single property.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@Tuzo:我认为使用 是可能的PropertyValidationFactory.GetPropertyValidator 方法。
@Tuzo: I think it is possible by using the PropertyValidationFactory.GetPropertyValidator method.