Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public BreakAwayContext()
- {
- ((IObjectContextAdapter)this).ObjectContext
- .ObjectMaterialized += (sender, args) =>
- {
- var entity = args.Entity as IObjectWithState;
- if (entity != null)
- {
- entity.State = State.Unchanged;
- entity.OriginalValues =
- BuildOriginalValues(this.Entry(entity).OriginalValues);
- }
- };
- }
- private static Dictionary<string, object> BuildOriginalValues(
- DbPropertyValues originalValues)
- {
- var result = new Dictionary<string, object>();
- foreach (var propertyName in originalValues.PropertyNames)
- {
- var value = originalValues[propertyName];
- if (value is DbPropertyValues)
- {
- result[propertyName] =
- BuildOriginalValues((DbPropertyValues)value);
- }
- else
- {
- result[propertyName] = value;
- }
- }
- return result;
- }
- private static void ApplyChanges<TEntity>(TEntity root)
- where TEntity : class, IObjectWithState
- {
- using (var context = new BreakAwayContext())
- {
- context.Set<TEntity>().Add(root);
- CheckForEntitiesWithoutStateInterface(context);
- foreach (var entry in context.ChangeTracker
- .Entries<IObjectWithState>())
- {
- IObjectWithState stateInfo = entry.Entity;
- entry.State = ConvertState(stateInfo.State);
- if (stateInfo.State == State.Unchanged)
- {
- ApplyPropertyChanges(entry.OriginalValues,
- stateInfo.OriginalValues);
- }
- }
- context.SaveChanges();
- }
- }
- private static void ApplyPropertyChanges(
- DbPropertyValues values,
- Dictionary<string, object> originalValues)
- {
- foreach (var originalValue in originalValues)
- {
- if (originalValue.Value is Dictionary<string, object>)
- {
- ApplyPropertyChanges(
- (DbPropertyValues)values[originalValue.Key],
- (Dictionary<string, object>)originalValue.Value);
- }
- else
- {
- values[originalValue.Key] = originalValue.Value;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement