Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Threading.Tasks;
  6. using System.Reflection;
  7. using Microsoft.EntityFrameworkCore;
  8. using Microsoft.EntityFrameworkCore.ChangeTracking;
  9. using Microsoft.EntityFrameworkCore.Metadata;
  10. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  11.  
  12.  
  13. namespace Rox.Extensions.DB
  14. {
  15. public static class DbContextExtensions
  16. {
  17. public static void SyncProperty<T>(this T target, T source, IEnumerable<string> properiesName = null)
  18. where T : class
  19. {
  20. Type t = typeof(T);
  21. var properties = t.GetRuntimeProperties();
  22. if (properiesName != null) properties = properties.Where(p => properiesName.Contains(p.Name));
  23.  
  24. foreach (var prop in properties)
  25. {
  26. var value = prop.GetValue(source, null);
  27. var valueTarget = prop.GetValue(target, null);
  28.  
  29. if (value != null && !value.Equals(valueTarget))
  30. prop.SetValue(target, value);
  31. }
  32. }
  33.  
  34. public static async Task<T> UpdateAsync<T>(this DbContext db, T entity, bool save = true)
  35. where T : class
  36. {
  37. var entry = db.Entry(entity);
  38. var primaryKey = entry.Metadata.FindPrimaryKey();
  39. if (primaryKey != null)
  40. {
  41. var nameKeys = primaryKey.Properties.Select(p => p.Name);
  42. var properies = entry.Metadata.GetProperties()?.Where(p => !nameKeys.Contains(p.Name) && !p.IsReadOnlyAfterSave && !p.IsReadOnlyBeforeSave && !p.IsShadowProperty)?.Select(p => p.Name);
  43. entity.SyncProperty(entity, properies);
  44. }
  45. else
  46. {
  47. entity.SyncProperty(entity);
  48. }
  49.  
  50. if (save)
  51. await db.SaveChangesAsync();
  52.  
  53. return entry.Entity;
  54. }
  55.  
  56. public static async Task<TEntity> AddOrUpdateAsync<TEntity, TContext>(this TContext db, TEntity entity, Expression<Func<TEntity, bool>> key, bool save = true)
  57. where TContext : DbContext, IDisposable
  58. where TEntity : class
  59. {
  60. if (entity == null)
  61. throw new ArgumentNullException(nameof(entity));
  62.  
  63. var dbEntity = await db.Set<TEntity>().FirstOrDefaultAsync(key);
  64. if (dbEntity != null)
  65. {
  66. dbEntity = await db.UpdateAsync(dbEntity, save: false);
  67. }
  68. else
  69. {
  70. dbEntity = db.Add(entity).Entity;
  71. }
  72.  
  73. if (save)
  74. await db.SaveChangesAsync();
  75.  
  76. return dbEntity;
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement