Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. public BreakAwayContext()
  2. {
  3. ((IObjectContextAdapter)this).ObjectContext
  4. .ObjectMaterialized += (sender, args) =>
  5. {
  6. var entity = args.Entity as IObjectWithState;
  7. if (entity != null)
  8. {
  9. entity.State = State.Unchanged;
  10.  
  11. entity.OriginalValues =
  12. BuildOriginalValues(this.Entry(entity).OriginalValues);
  13. }
  14. };
  15. }
  16.  
  17. private static Dictionary<string, object> BuildOriginalValues(
  18. DbPropertyValues originalValues)
  19. {
  20. var result = new Dictionary<string, object>();
  21. foreach (var propertyName in originalValues.PropertyNames)
  22. {
  23. var value = originalValues[propertyName];
  24. if (value is DbPropertyValues)
  25. {
  26. result[propertyName] =
  27. BuildOriginalValues((DbPropertyValues)value);
  28. }
  29. else
  30. {
  31. result[propertyName] = value;
  32. }
  33. }
  34. return result;
  35. }
  36.  
  37. private static void ApplyChanges<TEntity>(TEntity root)
  38. where TEntity : class, IObjectWithState
  39. {
  40. using (var context = new BreakAwayContext())
  41. {
  42. context.Set<TEntity>().Add(root);
  43.  
  44. CheckForEntitiesWithoutStateInterface(context);
  45.  
  46. foreach (var entry in context.ChangeTracker
  47. .Entries<IObjectWithState>())
  48. {
  49. IObjectWithState stateInfo = entry.Entity;
  50. entry.State = ConvertState(stateInfo.State);
  51. if (stateInfo.State == State.Unchanged)
  52. {
  53. ApplyPropertyChanges(entry.OriginalValues,
  54. stateInfo.OriginalValues);
  55. }
  56. }
  57.  
  58. context.SaveChanges();
  59. }
  60. }
  61.  
  62. private static void ApplyPropertyChanges(
  63. DbPropertyValues values,
  64. Dictionary<string, object> originalValues)
  65. {
  66. foreach (var originalValue in originalValues)
  67. {
  68. if (originalValue.Value is Dictionary<string, object>)
  69. {
  70. ApplyPropertyChanges(
  71. (DbPropertyValues)values[originalValue.Key],
  72. (Dictionary<string, object>)originalValue.Value);
  73. }
  74. else
  75. {
  76. values[originalValue.Key] = originalValue.Value;
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement