106 lines
3.9 KiB
C#
106 lines
3.9 KiB
C#
using System.Collections.Generic;
|
|
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 clientes = new List<Cliente>();
|
|
|
|
await using (var connection = new SqliteConnection(_connectionString))
|
|
{
|
|
await connection.OpenAsync();
|
|
await using (var cmd = connection.CreateCommand())
|
|
{
|
|
cmd.CommandText = @"SELECT Id, Nome, Email, CriadoEm
|
|
FROM Clientes
|
|
ORDER BY Id;";
|
|
await using (var reader = await cmd.ExecuteReaderAsync())
|
|
{
|
|
while (await reader.ReadAsync())
|
|
{
|
|
clientes.Add(new Cliente
|
|
{
|
|
Id = reader.GetInt32(0),
|
|
Nome = reader.GetString(1),
|
|
Email = reader.GetString(2),
|
|
CriadoEm = reader.GetDateTime(3)
|
|
});
|
|
}
|
|
}
|
|
}
|
|
connection.Close();
|
|
connection.Dispose();
|
|
}
|
|
return clientes;
|
|
}
|
|
|
|
public async Task AddClientAsync(Cliente c)
|
|
{
|
|
await using (var connection = new SqliteConnection(_connectionString))
|
|
{
|
|
await connection.OpenAsync();
|
|
await using (var cmd = connection.CreateCommand())
|
|
{
|
|
cmd.CommandText = @"
|
|
INSERT INTO Clientes (Nome, Email, CriadoEm)
|
|
VALUES (@nome, @email, @criado);";
|
|
cmd.Parameters.AddWithValue("@nome", c.Nome);
|
|
cmd.Parameters.AddWithValue("@email", c.Email);
|
|
cmd.Parameters.AddWithValue("@criado", c.CriadoEm);
|
|
await cmd.ExecuteNonQueryAsync();
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task UpdateClientAsync(Cliente c)
|
|
{
|
|
await using (var connection = new SqliteConnection(_connectionString))
|
|
{
|
|
await connection.OpenAsync();
|
|
await using (var cmd = connection.CreateCommand())
|
|
{
|
|
cmd.CommandText = @"
|
|
UPDATE Clientes
|
|
SET Nome = @nome,
|
|
Email = @email
|
|
WHERE Id = @id;";
|
|
cmd.Parameters.AddWithValue("@nome", c.Nome);
|
|
cmd.Parameters.AddWithValue("@email", c.Email);
|
|
cmd.Parameters.AddWithValue("@id", c.Id);
|
|
await cmd.ExecuteNonQueryAsync();
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task DeleteClientAsync(int id)
|
|
{
|
|
await using (var connection = new SqliteConnection(_connectionString))
|
|
{
|
|
await connection.OpenAsync();
|
|
await using (var cmd = connection.CreateCommand())
|
|
{
|
|
cmd.CommandText = @"DELETE FROM Clientes WHERE Id = @id;";
|
|
cmd.Parameters.AddWithValue("@id", id);
|
|
await cmd.ExecuteNonQueryAsync();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|