Files
workshop8/Data/SqliteClientRepository.cs
2025-07-30 16:25:48 -03:00

84 lines
2.5 KiB
C#

using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using Workshop8.Models;
namespace Workshop8.Data
{
public class SqliteClientRepository : IClientRepository
{
private readonly string _connectionString;
public SqliteClientRepository(IConfiguration configuration)
{
var dbConfig = configuration.GetSection("Database");
_connectionString = dbConfig.GetValue<bool>("UseRemote")
? dbConfig.GetValue<string>("Remote")
: dbConfig.GetValue<string>("Local");
}
public async Task<IEnumerable<Cliente>> GetAllClientsAsync()
{
var itens = new List<Cliente>();
using SqliteConnection conn = await GetConnection();
var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Id, Nome, Email, CriadoEm FROM Clientes";
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var p = new Cliente
{
Id = reader.GetInt32(0),
Nome = reader.GetString(1),
Email = reader.GetString(2),
CriadoEm = reader.GetDateTime(3)
};
itens.Add(p);
}
return itens;
}
private static async Task<SqliteConnection> GetConnection()
{
var conn = new SqliteConnection("Data Source=database.sqlite;");
await conn.OpenAsync();
return conn;
}
public async Task AddClientAsync(Cliente c)
{
var conn = await GetConnection();
var cmd = conn.CreateCommand();
cmd.CommandText = @"INSERT INTO Clientes (nome, email, criadoEm)
VALUES (@nome, @email, @criadoEm) ";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqliteParameter("@nome",c.Nome));
cmd.Parameters.Add(new SqliteParameter("@email",c.Email));
cmd.Parameters.Add(new SqliteParameter("@criadoEm",c.CriadoEm));
await using cmd.ExecuteNonQueryAsync();
}
public async Task UpdateClientAsync(Cliente c)
{
// TODO: implementar UPDATE
}
public async Task DeleteClientAsync(int id)
{
// TODO: implementar DELETE
}
}
}