Migrating an entity using the ADO.NET object infrastructure

I want to call the function of checking inside object objects just before they are saved in ObjectContext # SaveChanges (). Now I can independently track all the changed objects, and then scroll through them all and call their verification methods, but I assume that a simpler approach will implement some callback that the ObjectContext will call before saving each object. Can the latter be done at all? Is there an alternative?

+3
source share
2 answers

I figured out how to do it. Basically, we can catch the SavingChanges event of the ObjectContext and skip the newly added / modified objects to call their validation function. Here is 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);
    }
+8
source

Well, you could do it that way, but that means that you allow your clients to directly access the ObjectContext and, personally, I like to ignore them so that clients are more susceptible to testing.

I use the repository template and check when the save is called in the repository.

0
source

All Articles