-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserDal.cs
More file actions
44 lines (37 loc) · 1.31 KB
/
UserDal.cs
File metadata and controls
44 lines (37 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using Microsoft.EntityFrameworkCore;
using Todo.Data;
using Todo.Domain;
namespace Todo.Dal
{
public class UserDal
{
private readonly AppDbContext _context;
public UserDal(AppDbContext context)
{
_context = context;
}
public void AddUser(UserEntity user)
{
_context.Users.Add(user);
_context.SaveChanges();
}
/// <summary>
/// Adiciona um novo usuário ao banco de dados.
/// </summary>
/// <param name="model">Entidade do usuário a ser criada.</param>
/// <param name="ct">Token de cancelamento (opcional).</param>
public async Task AddUserAsync(UserEntity model, CancellationToken ct = default)
{
if (model is null)
throw new ArgumentNullException(nameof(model), "O modelo de usuário não pode ser nulo.");
// Evita duplicidade de Username
var exists = await _context.Users
.AsNoTracking()
.AnyAsync(u => u.Username == model.Username, ct);
if (exists)
throw new InvalidOperationException($"O nome de usuário '{model.Username}' já está em uso.");
await _context.Users.AddAsync(model, ct);
await _context.SaveChangesAsync(ct);
}
}
}