比方說你有一個實體,稱爲Car
這個類包含了需要被驗證的財產。
public class Car
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
// Accepted values have to be between 1 and 5.
public int NeedToBeValidatedRange { get; set; }
}
您必須爲我的示例中的所有實體創建一個基類,我將調用實體。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
/// This is the base class for all entities and it provide a change notfication.
public abstract class Entity : INotifyPropertyChanged
{
// Event fired when the property is changed!
public event PropertyChangedEventHandler PropertyChanged;
/// Called when int property in the inherited class is changed for ther others properties like (double, long, or other entities etc,) You have to do it.
protected void HandlePropertyChange(ref int value, int newValue, string propertyName)
{
if (value != newValue)
{
value = newValue;
this.Validate(propertyName);
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
/// Validate the property
/// <returns>
/// The list of validation errors
/// </returns>
private ICollection<ValidationResult> PropertyValidator(string propertyName)
{
var validationResults = new Collection<ValidationResult>();
PropertyDescriptor property = TypeDescriptor.GetProperties(this)[propertyName];
Validator.TryValidateProperty(
property.GetValue(this),
new ValidationContext(this, null, null) { MemberName = propertyName },
validationResults);
return validationResults;
}
/// Validates the given property and return all found validation errors.
private void Validate(string propName)
{
var validationResults = this.PropertyValidator(propName);
if (validationResults.Count > 0)
{
var validationExceptions = validationResults.Select(validationResult => new ValidationException(validationResult.ErrorMessage));
var aggregateException = new AggregateException(validationExceptions);
throw aggregateException;
}
}
}
,現在你得modfiy Car類,它應該是這樣的:
public class Car : Entity
{
private int id;
private int needToBeValidatedRange;
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id
{
get
{
return this.id;
}
set
{
this.HandlePropertyChange(ref this.id, value, "Id");
}
}
[Range(1, 5)]
public int NeedToBeValidatedRange
{
get
{
return this.needToBeValidatedRange;
}
set
{
this.HandlePropertyChange(ref this.needToBeValidatedRange, value, "NeedToBeValidatedRange ");
}
}
}
某處在您創建的汽車實體的用戶界面:
Car car1 = new Car();
car1.NeedToBeValidatedRange = 3; // This will work!
Car car2 = new Car();
car2.NeedToBeValidatedRange = 6; // This will throw ValidationException
- WPF支持非常好的ValidationException。
- Winforms支持部分ValidationException,但現在您可以自由處理此問題。
的OP已要求EF 5,但希望它適用於EF 4.1的! –
它適用於4.1. –