Search code examples
wcfvalidationcollectionsdatacontract

Validation of elements in a collection of a WCF data contract


We have a WCF service that uses Microsoft.Practices.EnterpriseLibrary.Validation and receives an object like so (simplified):

[DataMember]
[NotNullValidator]
public string Name { get; set; }

[DataMember]
public IList<Appointment> Appointments { get; set; }

The Appointment DataContract could look like:

[DataMember]
[NotNullValidator]
public string Description { get; set; }

Now the problem is that the validation of the Name property seems to work, but the Description isn't validated. So you can't pass a request with an empty Name, but you can pass a request with a Name and a list of Appointments with empty Descriptions.

Is it normal that WCF doesn't validate the elements of a collection in a DataContract?


Solution

  • Well, we solved it by adding SelfValidation:

    [HasSelfValidation]
    public class Client
    {
        [DataMember]
        [NotNullValidator]
        public string Name { get; set; }
    
        [DataMember]
        public IList<Appointment> Appointments { get; set; }
    
        [SelfValidation]
        {
            foreach (var appointment in Appointments)
            {
                results.AddAllResults(Validation.Validate(appointment));
            }
        }
    }