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();
}
The entry has
Entityproperty 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
SaveChangesto 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 tobase.SaveChangeswill 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
Documentinstances prior toParagraphto make sure that directories are created before you want to insert files, etc. Simply this logic doesn’t belong toSaveChangesmethod and should not be called fromSaveChangesmethod.