views:

332

answers:

1

Hi

In my database, I have a composite unique key constraint (CustomerId, Name) on a entity. I want to test if the unique constraint is upheld before submitting changes to the database. The user can customize the Name attribute on the entity, so I would like to make a custom validator that validates the name property, but while doing it, I need access to the CustomerId property as well. How do I do that?

I an using WCSF, which means I am stuck in Entlib 3.1 and the included VAB, but I guess it is possible to switch to EntLib 4.1's VAB without breaking WCSF.

Regards, Egil.

A: 

The trick is to create a validator for your entity, not for one of the properties of that entity. You can write a self validation on your entity as follows:

[HasSelfValidation]
public class MyEntity
{
    public int CustomerId { get; set; }
    public string Name { get; set; }

    [SelfValidation]
    public void ValidateRange(ValidationResults results)
    {
        bool isUnique = [query the database here]

        if (!isUnique)
        {
            results.AddResult(new ValidationResult(
                "CustomerId and Name are not unique", this, "", "", null));
        }
    }
}

I must say I'm not familiar with the feature set of VAB 3.1, so I'm not 100% sure this works on 3.1. It works on 4.1 though. If you don't like self validation, you can also write a custom validator and hook it up in the configuration file. Look at this stackoverflow answer for more info on how to do this.

Steven