I am working on a three tier architecture in MVC with Business Objects layer, Service layer and web layer.
The business objects layer contains DTO (data transfer object).
The service layer processes the DTO and contains the business logic.
One of my DTO is like below:
public class InsertCompanyGroupDto
{
public InsertCompanyGroupDto()
{
this.CompanyGroupAddressDetails = new InsertAddressDto();
}
public InsertAddressDto CompanyGroupAddressDetails { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
[StringLength(100, ErrorMessage = "The {0} can not exceed {1} characters long.")]
public string CompanyGroupName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
[StringLength(200, ErrorMessage = "The {0} can not exceed {1} characters long.")]
public string SiteUrl { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
[StringLength(20, ErrorMessage = "The {0} can not exceed {1} characters long.")]
public string UserNameTag { get; set; }
}
In this code, I am using InsertAddressDto inside the Insert Company Group DTO.
Both have validations. Please have a look at the Insert Address DTO.
public class InsertAddressDto
{
[Min(1, ErrorMessage = "{0} should be minimum of {1}.")]
[Required(ErrorMessage = "The {0} is required.")]
public short AddressTypeId { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
[StringLength(100, ErrorMessage = "The {0} can not exceed {1} characters long.")]
public string Address1 { get; set; }
[StringLength(100, ErrorMessage = "The {0} can not exceed {1} characters long.")]
public string Address2 { get; set; }
}
from the above code, I am passing only one request as JSON, which contains
{
"CompanyGroupName":"CG5",
"SiteUrl":"http://localhost:33570/MultiChoice5",
"UserNameTag":"Aker1",
"SourceCode":"Test22",
"PageFooter":"test22",
"CreatedById":"1",
"AddressTypeId":"6",
"Address1":"test 1",
"Town":"testt",
"Postcode":"24234",
"CountryId":"1",
"CreatedById":"1"
}
I am using the following code inside the DTO for validation.
public IEnumerable<ValidationResult> Validate()
{
return Validate(new ValidationContext(this));
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, results, true);
return results;
}
I am using this code in both DTOs (company group and address).
Validation only works in InsertCompanyGRoupDTO, but not in InsertAddressDTO.
How can I rectify this?
I need to know how to validate two DTOs (one within another) at the same time?