From 64f4cdc85eeba3ba0d61a1b331822da362d276ef Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 23 Mar 2025 20:46:11 +0100 Subject: [PATCH] Changed CreateUserAsync to avoid silent transaction failure --- MainProject/Services/UserService.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/MainProject/Services/UserService.cs b/MainProject/Services/UserService.cs index c5f5766..1e0fdf8 100644 --- a/MainProject/Services/UserService.cs +++ b/MainProject/Services/UserService.cs @@ -11,6 +11,7 @@ public interface IUserService { Task GetUserByIdAsync(int id); Task GetUserByGuidAsync(string guid); + Task GetUserByEmailAsync(string email); Task GetUserByUsernameAndPassword(string email, string password); Task CheckIfEmailIsValid(string email, string? guid = ""); Task CreateUserAsync(CreateUserRequestData data, Role role); @@ -70,6 +71,11 @@ public class UserService : BaseService, IUserService return await this.GetUsersQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); } + public async Task GetUserByEmailAsync(string email) + { + return await this.GetUserByEmailQueryable(email).FirstOrDefaultAsync(); + } + public async Task GetUserByUsernameAndPassword(string email, string password) { User? user = await this.GetUserByEmailQueryable(email).FirstOrDefaultAsync(); @@ -79,7 +85,6 @@ public class UserService : BaseService, IUserService Console.WriteLine(encryptedPassword); } - return user; } @@ -106,14 +111,22 @@ public class UserService : BaseService, IUserService { User? user = null; - using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + await using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try { var tempUser = this.CreateUserData(data, role); await _sqlServerContext.Users.AddAsync(tempUser); await _sqlServerContext.SaveChangesAsync(); - await (await transaction).CommitAsync(); + + await transaction.CommitAsync(); user = tempUser; } + catch + { + await transaction.RollbackAsync(); + throw; + } return user; }