Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept entity saving with ADO.NET Entities Framework

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?

like image 371
Buu Nguyen Avatar asked Nov 16 '25 13:11

Buu Nguyen


1 Answers

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);
    }
like image 199
Buu Nguyen Avatar answered Nov 19 '25 07:11

Buu Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!