Changed CreateUserAsync to avoid silent transaction failure

This commit is contained in:
2025-03-23 20:46:11 +01:00
parent 5d104d5dc8
commit 64f4cdc85e

View File

@@ -11,6 +11,7 @@ public interface IUserService
{ {
Task<User?> GetUserByIdAsync(int id); Task<User?> GetUserByIdAsync(int id);
Task<User?> GetUserByGuidAsync(string guid); Task<User?> GetUserByGuidAsync(string guid);
Task<User?> GetUserByEmailAsync(string email);
Task<User?> GetUserByUsernameAndPassword(string email, string password); Task<User?> GetUserByUsernameAndPassword(string email, string password);
Task<bool> CheckIfEmailIsValid(string email, string? guid = ""); Task<bool> CheckIfEmailIsValid(string email, string? guid = "");
Task<User?> CreateUserAsync(CreateUserRequestData data, Role role); Task<User?> CreateUserAsync(CreateUserRequestData data, Role role);
@@ -70,6 +71,11 @@ public class UserService : BaseService, IUserService
return await this.GetUsersQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); return await this.GetUsersQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync();
} }
public async Task<User?> GetUserByEmailAsync(string email)
{
return await this.GetUserByEmailQueryable(email).FirstOrDefaultAsync();
}
public async Task<User?> GetUserByUsernameAndPassword(string email, string password) public async Task<User?> GetUserByUsernameAndPassword(string email, string password)
{ {
User? user = await this.GetUserByEmailQueryable(email).FirstOrDefaultAsync(); User? user = await this.GetUserByEmailQueryable(email).FirstOrDefaultAsync();
@@ -79,7 +85,6 @@ public class UserService : BaseService, IUserService
Console.WriteLine(encryptedPassword); Console.WriteLine(encryptedPassword);
} }
return user; return user;
} }
@@ -106,14 +111,22 @@ public class UserService : BaseService, IUserService
{ {
User? user = null; User? user = null;
using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) await using var transaction = await _sqlServerContext.Database.BeginTransactionAsync();
try
{ {
var tempUser = this.CreateUserData(data, role); var tempUser = this.CreateUserData(data, role);
await _sqlServerContext.Users.AddAsync(tempUser); await _sqlServerContext.Users.AddAsync(tempUser);
await _sqlServerContext.SaveChangesAsync(); await _sqlServerContext.SaveChangesAsync();
await (await transaction).CommitAsync();
await transaction.CommitAsync();
user = tempUser; user = tempUser;
} }
catch
{
await transaction.RollbackAsync();
throw;
}
return user; return user;
} }