11namespace MADE . Data . EFCore . Extensions
22{
33 using System ;
4+ using System . Collections . Generic ;
45 using System . Linq ;
56 using System . Linq . Expressions ;
67 using System . Threading ;
78 using System . Threading . Tasks ;
89 using Microsoft . EntityFrameworkCore ;
10+ using Microsoft . EntityFrameworkCore . ChangeTracking ;
911
1012 /// <summary>
1113 /// Defines a collection of extensions for <see cref="DbContext"/> types.
@@ -24,7 +26,10 @@ public static class DbContextExtensions
2426 /// <exception cref="DbUpdateConcurrencyException">A concurrency violation is encountered while saving to the database.
2527 /// A concurrency violation occurs when an unexpected number of rows are affected during save.
2628 /// 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 )
29+ public static async Task UpdateAsync < T > (
30+ this DbContext context ,
31+ T entity ,
32+ CancellationToken cancellationToken = default )
2833 {
2934 context . Update ( entity ) ;
3035 await context . SaveChangesAsync ( cancellationToken ) ;
@@ -42,5 +47,34 @@ public static void RemoveWhere<T>(this DbSet<T> set, Expression<Func<T, bool>> p
4247 IQueryable < T > toRemove = set . Where ( predicate ) ;
4348 set . RemoveRange ( toRemove ) ;
4449 }
50+
51+ /// <summary>
52+ /// Sets the dates of <see cref="EntityBase"/> entities being tracked in an added or modified state.
53+ /// <para>
54+ /// It is best to call this method in an override of the DbContext.SaveChangesAsync method in your data context.
55+ /// </para>
56+ /// </summary>
57+ /// <param name="context">The <see cref="DbContext"/> to update entity dates for.</param>
58+ public static void SetEntityDates ( this DbContext context )
59+ {
60+ IEnumerable < EntityEntry > entries = context . ChangeTracker
61+ . Entries ( )
62+ . Where (
63+ entry => entry . Entity is EntityBase &&
64+ ( entry . State == EntityState . Added || entry . State == EntityState . Modified ) ) ;
65+
66+ DateTime now = DateTime . UtcNow ;
67+
68+ foreach ( EntityEntry entry in entries )
69+ {
70+ var entity = ( EntityBase ) entry . Entity ;
71+ entity . UpdatedDate = now ;
72+
73+ if ( entry . State == EntityState . Added && entity . CreatedDate == DateTime . MinValue )
74+ {
75+ entity . CreatedDate = now ;
76+ }
77+ }
78+ }
4579 }
46- }
80+ }
0 commit comments