user672118
user672118

Reputation:

Entity Framework DbContext Override SaveChanges For Each Model

I have a couple models associated with a DbContext. How can I override SaveChanges to do something different based on the model being saved?

For example, let's say I have two models, Document and Paragraph. How can I override SaveChanges so that a directory is created when a Document is added and that a file is created when a Paragraph is added.

Here is my attempt at doing this so far.

public int override SaveChanges()
{
    ChangeTracker.DetectChanges();

    var context = ((IObjectContextAdapter)this).ObjectContext;
    var stateEntries = context.ObjectStateManager.GetObjectStateEntries(
        EntityState.Added
        | EntityState.Modified
        | EntityState.Deleted
    ).ToList();

    foreach (var entry in stateEntries)
    {
        if (!entry.IsRelationship)
        {
            switch (entry.State)
            {
                case EntityState.Added:
                    break;

                case EntityState.Modified:
                    break;

                case EntityState.Deleted:
                    break;
            }
        }
    }

    return base.SaveChanges();
}

Upvotes: 0

Views: 2570

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

The entry has Entity property which holds instance of your processed entity so you can check instance's type and theoretically do whatever logic you want to do.


You should not use SaveChanges to do anything else than processing your entities for persistence to database - that breaks the separation of concerns. The context is adapter between your application logic and database - nothing more. Moreover whole this idea of integrating file system operations with database operations needs much more complex and careful handling to solve the situation when any operation fails. In your current scenario any failure in call to base.SaveChanges will result in orphan directories or files in your file system - you need to use transactional file system and run but database and file system operation in the same transaction or you must implement manual file system compensation.

Another problem with your code is that you must process Document instances prior to Paragraph to make sure that directories are created before you want to insert files, etc. Simply this logic doesn't belong to SaveChanges method and should not be called from SaveChanges method.

Upvotes: 2

Related Questions