-
Notifications
You must be signed in to change notification settings - Fork 4
8. Handle Validation Errors
codeplanner edited this page Dec 31, 2014
·
4 revisions
A simple way to add rules on your model is to use the attributes available from DataAnnotations. So now we just add the Required attribute as well as the Range attribute to our Person enity.
public class Person : PersistentEntity
{
[Required]
public string Name { get; set; }
[Range(1,20, ErrorMessage = "Age have to be between 1 - 20")]
public int Age { get; set; }
}
To get a instance of the service see using the service layer
//Create person with an invalid Age and omit the Name
//This will give 2 errors
var p = new Person { Age = 30 };
//Save or update
var result = personService.SaveOrUpdate(p);
if (!result.IsValid)
{
foreach (var error in result.ValidationErrors)
{
Console.WriteLine("Property: {0} has {1} errors", error.Key, error.Value.Count);
foreach (var message in error.Value)
{
Console.WriteLine("Err: {0}", message);
}
}
}
The code above would output something like
Property: Name has 1 errors
Err: The Name field is required.
Property: Age has 1 errors
Err: Age have to be between 1 - 20
This is not really business logic, so the next step is to look at how you can add custom logic in the service layer
