Tuesday, June 14, 2011

Using lambdas to wrap model validations in C#

In .NET, I have found the following method useful when wrapping validation around any CRUD operation:

private IEnumerable<ValidationResult> PerformWithModelValidation(object model, Action code_to_execute)
        {
            var results = new List<ValidationResult>();
            ValidationContext context = new ValidationContext(model, null, null);
            bool valid = Validator.TryValidateObject(model, context, results, true);
            if (valid)
            {
                code_to_execute();
            }
            return results;
        }

//How to use the method above:

PerformWithModelValidation(new_product, () =>
{
	MyRepository.Add(new_product);
	MyRepository.SaveChanges();
}
);

0 comments: