views:

32

answers:

1

Hi! I've done a fair amount of searching but I've yet to find an easy way to validate EntityFramework 4.0 entities passed accross the wire via WCF Data Services. Basically, I want to do something on the client like:

        Proxy.MyEntities entities = new Proxy.MyEntities(
            new Uri("http://localhost:2679/Service.svc"));

        Proxy.Vendor vendor = new Proxy.Vendor();

        vendor.Code = "ABC/XYZ";
        vendor.Status = "ACTIVE";

        // I'd like to do something like the following:
        vendor.Validate();

        entities.AddToVendors(vendor);

        entities.SaveChanges();

Any help in this regard would be greatly appreciated!

A: 

If I were you I would use the System.ComponentModel.DataAnnotations framework.

There are many examples on the web for it.

You can use the ValidationAttributes like required, range etc and create your own attribute to perform custom validation.

See below how to validate an entity.

Type objectType = entity.GetType();

Dictionary<string, string> errors = new Dictionary<string, string>();

foreach (PropertyInfo propertyInfo in objectType.GetProperties().Where(w => w.CanRead))
{
    object value = propertyInfo.GetValue(entity, null);

    foreach (ValidationAttribute validator in propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), false))
    {
        if (!validator.IsValid(value))
        {
            errors.Add(propertyInfo.Name, validator.ErrorMessage);
        }
    }
}

I hope this helps if you need anything else just ask

Regard

Daniel

dmportella