@@ -76,5 +76,64 @@ public static void SetEntityDates(this DbContext context)
7676 }
7777 }
7878 }
79+
80+ /// <summary>
81+ /// Attempts to save all changes made in this context to the database.
82+ /// </summary>
83+ /// <param name="context">The <see cref="DbContext"/>.</param>
84+ /// <param name="onError">An exception for handling the exception thrown, for example, event logging.</param>
85+ /// <param name="cancellationToken"> A <see cref="CancellationToken" /> to observe while waiting for the task to complete. </param>
86+ /// <returns>
87+ /// True if the changes saved successfully; otherwise, false.
88+ /// </returns>
89+ public static async Task < bool > TrySaveChangesAsync (
90+ this DbContext context ,
91+ Action < Exception > onError = null ,
92+ CancellationToken cancellationToken = default )
93+ {
94+ try
95+ {
96+ await context . SaveChangesAsync ( cancellationToken ) ;
97+ return true ;
98+ }
99+ catch ( DbUpdateException ex )
100+ {
101+ onError ? . Invoke ( ex ) ;
102+ }
103+
104+ return false ;
105+ }
106+
107+ /// <summary>
108+ /// Attempts to perform an action on the data context.
109+ /// </summary>
110+ /// <param name="context">The <see cref="DbContext"/>.</param>
111+ /// <param name="action">The action to run.</param>
112+ /// <param name="onError">An exception for handling the exception thrown, for example, event logging.</param>
113+ /// <typeparam name="TContext">The type of data context.</typeparam>
114+ /// <returns>True if the action ran successfully; otherwise, false.</returns>
115+ public static async Task < bool > TryAsync < TContext > (
116+ this TContext context ,
117+ Func < TContext , Task > action ,
118+ Action < Exception > onError = null )
119+ where TContext : DbContext
120+ {
121+ if ( action == null )
122+ {
123+ return false ;
124+ }
125+
126+ try
127+ {
128+ await action . Invoke ( context ) ;
129+ return true ;
130+ }
131+ catch ( Exception ex )
132+ {
133+ onError ? . Invoke ( ex ) ;
134+ }
135+
136+ return false ;
137+ }
79138 }
80139}
0 commit comments