|
| 1 | +namespace MADE.Data.EFCore.Extensions |
| 2 | +{ |
| 3 | + using System; |
| 4 | + using System.Linq; |
| 5 | + using System.Linq.Expressions; |
| 6 | + using System.Threading; |
| 7 | + using System.Threading.Tasks; |
| 8 | + using Microsoft.EntityFrameworkCore; |
| 9 | + |
| 10 | + /// <summary> |
| 11 | + /// Defines a collection of extensions for <see cref="DbContext"/> types. |
| 12 | + /// </summary> |
| 13 | + public static class DbContextExtensions |
| 14 | + { |
| 15 | + /// <summary> |
| 16 | + /// Updates an entity within the context and saves the changes. |
| 17 | + /// </summary> |
| 18 | + /// <param name="context">The <see cref="DbContext"/>.</param> |
| 19 | + /// <param name="entity">The entity to update.</param> |
| 20 | + /// <param name="cancellationToken">The cancellation token.</param> |
| 21 | + /// <typeparam name="T">The type of entity to update.</typeparam> |
| 22 | + /// <returns>An asynchronous operation.</returns> |
| 23 | + /// <exception cref="DbUpdateException">An error is encountered while saving to the database.</exception> |
| 24 | + /// <exception cref="DbUpdateConcurrencyException">A concurrency violation is encountered while saving to the database. |
| 25 | + /// A concurrency violation occurs when an unexpected number of rows are affected during save. |
| 26 | + /// This is usually because the data in the database has been modified since it was loaded into memory.</exception> |
| 27 | + public static async Task UpdateAsync<T>(this DbContext context, T entity, CancellationToken cancellationToken = default) |
| 28 | + { |
| 29 | + context.Update(entity); |
| 30 | + await context.SaveChangesAsync(cancellationToken); |
| 31 | + } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Removes entities from a <see cref="DbSet{TEntity}"/> using the specified predicate. |
| 35 | + /// </summary> |
| 36 | + /// <param name="set">The data set to remove entities from.</param> |
| 37 | + /// <param name="predicate">The function for determining the items to remove.</param> |
| 38 | + /// <typeparam name="T">The type of entity to remove.</typeparam> |
| 39 | + public static void RemoveWhere<T>(this DbSet<T> set, Expression<Func<T, bool>> predicate) |
| 40 | + where T : class |
| 41 | + { |
| 42 | + IQueryable<T> toRemove = set.Where(predicate); |
| 43 | + set.RemoveRange(toRemove); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments