1

As part of the save operation in my DbContext, I need to serialize extended information to be stored in a binary field in the database.

I've written the following method to intercept all Client objects that have been added or modified to ensure the serialization takes place before they are saved. I'm wondering if there is a better way of doing this or if there will be problems created by this method.

public int Save()
{
    foreach (Client client in this.Context.Local.Clients)
    {   
        EntityState state = this.Context.Entry(client).State;
        if (state == EntityState.Added || state == EntityState.Modified)
        {
            client.SerializeExtended();
        }   
    }
    return this.Context.SaveChanges();
}
2
  • Override the DbContext.SaveChanges method and place your serialization logic there. Also call ChangeTracker.DetectChanges method before your custom code. Commented Nov 28, 2012 at 19:12
  • I agree overriding SaveChanges would be an elegant way to do this. In my case, I'm using a repository that doesn't expose the underlying context, so the Save method is used to trigger a save without the consumer knowing anything about the data provider. Commented Nov 28, 2012 at 20:40

1 Answer 1

2

override DbContext.SaveChanges method.

protected override int SaveChanges()
{
     foreach (var entry in ChangeTracker.Entries<Clients())
     {
        var entity = entry.Entity;
        if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
        {
            entry.Entity.SerializeExtended();
        }
     }
     base.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'll plus 1 this as it is a good suggestion. See comment above for the reason why I'm using a custom Save method in my repository. Perhaps I should have been more clear, I'm wondering if cycling through the list of local Client objects and hunting for adds and updates is the best (or only) way to go in this scenario. Thanks for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.