Reputation: 2035
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();
}
Upvotes: 1
Views: 144
Reputation: 7591
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();
}
Upvotes: 2