views:

673

answers:

2

I want to invoke a validation function inside the entities objects right before they are stored with ObjectContext#SaveChanges(). Now, I can keep track of all changed objects myself and then loop through all of them and invoke their validation methods, but I suppose an easier approach would be implement some callback that ObjectContext will invoke before saving each entity. Can the latter be done at all? Is there any alternative?

A: 

Well, you could do it that way, but it means that you're allowing your clients to directly access the ObjectContext, and, personally, I like to abstract that away, in order to make the clients more testable.

What I do is use the repository pattern, and do the validation when save is called on a repository.

Craig Stuntz
Thanks - that's a good one. But I tend to start simple first and only add more layers of abstraction only when necessary. That said, the client tests does dig through EF and DB without any mock - not quite *unit* test but so far that works well.
Buu Nguyen
+2  A: 

I've figured out how. Basically, we can intercept SavingChanges event of ObjectContext and loop through the newly added/modified entities to invoke their validation function. Here's the code I used.

    partial void OnContextCreated()
    {
        SavingChanges += PerformValidation;
    }

    void PerformValidation(object sender, System.EventArgs e)
    {
        var objStateEntries = ObjectStateManager.GetObjectStateEntries(
            EntityState.Added | EntityState.Modified);

        var violatedRules = new List<RuleViolation>();
        foreach (ObjectStateEntry entry in objStateEntries)
        {
            var entity = entry.Entity as IRuleValidator;
            if (entity != null)
                violatedRules.AddRange(entity.Validate());
        }
        if (violatedRules.Count > 0)
            throw new ValidationException(violatedRules);
    }
Buu Nguyen