DbSetExtensions.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Common;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.EntityFrameworkCore.Infrastructure;
  10. using Microsoft.EntityFrameworkCore.Internal;
  11. using Microsoft.EntityFrameworkCore.Storage;
  12. using Microsoft.Extensions.DependencyInjection;
  13. using EasyDevCore.Common;
  14. using System.Data;
  15. using System.Runtime.CompilerServices;
  16. using System.Dynamic;
  17. using System.Collections;
  18. using System.Reflection;
  19. using Microsoft.EntityFrameworkCore.Metadata;
  20. using Microsoft.EntityFrameworkCore.Query;
  21. using System.Linq.Expressions;
  22. namespace EasyDevCore.Database
  23. {
  24. /// <summary>
  25. ///
  26. /// </summary>
  27. public static class DbSetExtensions
  28. {
  29. /// <summary>
  30. /// Gets the context.
  31. /// </summary>
  32. /// <typeparam name="TEntity">The type of the entity.</typeparam>
  33. /// <param name="dbSet">The database set.</param>
  34. /// <returns></returns>
  35. public static DbContext GetContext<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class
  36. {
  37. object internalSet = dbSet
  38. .GetType()
  39. .GetField("_internalSet", BindingFlags.NonPublic | BindingFlags.Instance)
  40. .GetValue(dbSet);
  41. object internalContext = internalSet
  42. .GetType()
  43. .BaseType
  44. .GetField("_internalContext", BindingFlags.NonPublic | BindingFlags.Instance)
  45. .GetValue(internalSet);
  46. return (DbContext)internalContext
  47. .GetType()
  48. .GetProperty("Owner", BindingFlags.Instance | BindingFlags.Public)
  49. .GetValue(internalContext, null);
  50. }
  51. /// <summary>
  52. /// Saves the change.
  53. /// </summary>
  54. /// <typeparam name="TEntity">The type of the entity.</typeparam>
  55. /// <param name="dbSet">The database set.</param>
  56. /// <returns></returns>
  57. public static int SaveChange<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class
  58. {
  59. var context = (EasyDbContext)dbSet.GetContext();
  60. return context.SaveChangeEntity(dbSet.GetType());
  61. }
  62. /// <summary>
  63. /// Saves the change asynchronous.
  64. /// </summary>
  65. /// <typeparam name="TEntity">The type of the entity.</typeparam>
  66. /// <param name="dbSet">The database set.</param>
  67. /// <returns></returns>
  68. public static async Task<int> SaveChangeAsync<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class
  69. {
  70. var context = (EasyDbContext)dbSet.GetContext();
  71. return await context.SaveChangeEntityAsync(dbSet.GetType()).ConfigureAwait(false);
  72. }
  73. }
  74. }