Let me preface this question and state that using Entity Framework is not an option for us.
In our financial organization we have business entities that are going to be used across solutions. Some have a UI others do not. Validation and business rules must be contained within the entity.
I code against a DAL and DTOs that are generated for me and those DALs use procs to operate CRUD on the DB (could be SQL could be Oracle).
So as I am creating MVC, WCF, Console apps etc.. the question has been nagging if a better method of validation could be implemented.
Here is a couple typical properties in an entity object:
[DefaultValue("")]
public string Branch {
get { return _branch; }
set {
if (value != null && value == _branch) return;
const string propertyName = "Branch";
ValidationInstance.Clear(propertyName);
ValidationInstance.ValidateRequired(propertyName, value);
ValidationInstance.ValidateNumeric(propertyName, value);
ValidationInstance.ValidateLength(propertyName, value, 2);
_branch = value;
if (EntityState != EntityStateType.New)
EntityState = EntityStateType.Changed;
}
}
[DefaultValue(0)]
public decimal HighDefermentMargin {
get { return _highDefermentMargin; }
set {
if (value == _highDefermentMargin) return;
const string propertyName = "HighDefermentMargin";
ValidationInstance.Clear(propertyName);
ValidationInstance.ValidateRange(propertyName, value);
_highDefermentMargin = value;
if (EntityState != EntityStateType.New)
EntityState = EntityStateType.Changed;
}
}
As you can see there is a mix of data annotations and explicit calls to a validation class to perform increasingly detailed validation.
In an MVC app we painstakingly duplicate validation on the ViewModel so we get client side and server side validation. Here is the ViewModel version of the same property from above:
[Required]
[Range(0.0, 99.99)]
[Display(Name = "High Deferment Margin")]
public decimal HighDefermentMargin { get; set; }
The main difference here is that the validation in the entity loads the errors into an errors collection on the Validation class which can be queried at the time the entity goes to save itself. If(!IsValid) then throw a custom exception that contains the array of errors. The controller loops thru them and adds them to ModelState.
I’m starting to work on some classes that have literally a couple hundred fields. Even if they get broken down by OO the number of fields is still very high. These are loan certifications etc that have a lot of data for a single record. Having to write out validation on that many properties makes me want to vomit. I can’t just write a utility to generate the entities and validation because business rules are what drive the validation, not the database. Meaning a field may be nullable in the db but not allowed to be persisted as null based on business rules, or the field can be null but only if a separate field has a value, etc..
So, can using just the data annotations in the View Model AND the entity the same way achieve the same results? I can write custom validators for the non-standard validation and then business rules for more complex stuff. Will validation errors bethrown up to a higher level from the entity so the UI can inform the user in the same friendly way as ModelState? What are others doing in this same kind of situation?
In general a validation attribute on a property can get different validation results (validation passing or not) depending if it is evaluated in the UI Layer, BUsiness Layer or DAL. Consider for instance a Required attribute if applied on the ViewModel it can fail, but then in the Business Layer it can pass simply because the value that the user has not provided has been provided from other sources.
However, validation rules like the format of an email…always get the same result. However, there are scurity issues that may required the validation to be repeated in the business layer…simply because the web server is more exposed to attacks and is more vulnerable. However, repeating twice the same validation doesn’t imply writing twice the code. You can collect all attributes that you would like to apply in several layers in a common dll where you define MetaDataTypes that you apply to the various versions (ViewModel, BL, DAL) of the same conceptual entity. This way, you fulfill security requirements without duplicating code.
As suggested by saravanan you can use exceptions to communicate validation errors discovered in other layers to the UI Layer (you can also configure WCF to communicate exception details to the client)