I need validation for all DTO objects using System.ComponentModel.DataAnnotations. You can see how I implemented. Idea is to have one abstract class that will be inherited in all dto classes. This abstract class have check if object is valid and get all validation results.
Is this good approach?
What do you think?
dto base class :
public abstract class DtoBase : IValidatableObject
{
public virtual IEnumerable<ValidationResult> GetValidationResult()
{
return Validate(new ValidationContext(this));
}
public bool IsValid()
{
return Validate(new ValidationContext(this)).Count() == 0;
}
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, results, true);
return results;
}
}
dto work item :
public class WorkItemDto : DtoBase
{
public WorkItemDto()
{
}
public int Id { get; set; }
[StringLength(500, MinimumLength = 200)]
public string Description { get; set; }
[Range(20, 5000)]
public int ItemNumValue { get; set; }
public ICollection<ItemUsageDto> Usage { get; set; }
}
Example how to use in wpf or in mvc project (it have to work in any client):
var item = new WorkItemDto();
item.Description = "my descryption";
item.ItemNumValue = 5;
item.Id = 7;
var isValid = item.IsValid();
var allResults = item.GetValidationResult();