Skip to content

Commit a29d50f

Browse files
committed
Added data context extensions for trying to perform actions
1 parent 841ff5b commit a29d50f

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

src/MADE.Data.EFCore/Extensions/DbContextExtensions.cs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)