Taking the simple Entity below...
public class MyEntity
{
[MaxLength(100)]
[Required]
public string Name { get; private set; }
}
...is it possible to read the data annotations which are decorating the "Name" property and validate the value specified in the ChangeName method so the ValidationResults can be concatenated to other validation results. I assume using MethodInfo or PropertyInfo objects some how?
I have this but it feels very clumsey.
public ValidationResult ChangeName(string value)
{
var property = GetType().GetProperty("Name");
var attribute = property.GetCustomAttributes(typeof(MaxLengthAttribute), true)[0] as MaxLengthAttribute;
if (attribute == null) return null; //yield break;
if (value.Length > attribute.Length)
{
return new ValidationResult(NameValidation.NameTooLong);
}
return null;
}
I want to be able to call ChangeName(value) from a method in my validator like so..
private IEnumerable<ValidationResult> ValidateMyEntity(MyEntityAddCommand command)
{
MyEntity myEntity = new MyEntity();
yield return myEntity.ChangeName(command.Name);
}
Most things I have read so far say data annotations are for CRUD not DDD, but why not use them as they are a nice way to describe validation behaviour and it will be consistent with the data annotation validation on my MVC view model. Is there a better or more succinct way I can do this? All advice appreciated.