DbSetExtension.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.EntityFrameworkCore.Infrastructure;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Text;
  8. namespace GreenTree.Strohrmann.ERP.Domain.Extension
  9. {
  10. public static class DbSetExtension
  11. {
  12. /// <summary>
  13. /// Removes a sequence of entities from a specific DbSet filtered by a predicate
  14. /// </summary>
  15. /// <typeparam name="TEntity">Entity type.</typeparam>
  16. /// <param name="dbSet">Database DbSet.</param>
  17. /// <param name="expression">Filter expression.</param>
  18. public static void RemoveWhere<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> expression)
  19. where TEntity : class
  20. {
  21. var entities = dbSet
  22. .Where(expression);
  23. dbSet.RemoveRange(entities);
  24. }
  25. /// <summary>
  26. /// Removes a sequence of entities from a specific DbSet filtered by a predicate and inserts a set of new entities for them
  27. /// </summary>
  28. /// <typeparam name="TEntity">Entity type.</typeparam>
  29. /// <param name="dbSet">Database DbSet.</param>
  30. /// <param name="expression">Filter expression.</param>
  31. /// <param name="newEntities">New entities.</param>
  32. public static void ReplaceWhere<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> expression,
  33. IEnumerable<TEntity> newEntities)
  34. where TEntity : class
  35. {
  36. RemoveWhere(dbSet, expression);
  37. dbSet.AddRange(newEntities);
  38. }
  39. }
  40. }