97 lines
3.2 KiB
C#
97 lines
3.2 KiB
C#
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Workshop8.Models;
|
|
using System;
|
|
|
|
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 clients = new List<Cliente>();
|
|
|
|
using var connection = new SqliteConnection(_connectionString);
|
|
await connection.OpenAsync();
|
|
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = "SELECT Id, Nome, Email, CriadoEm FROM Clientes";
|
|
|
|
using var reader = await command.ExecuteReaderAsync();
|
|
while (await reader.ReadAsync())
|
|
{
|
|
clients.Add(new Cliente
|
|
{
|
|
Id = reader.GetInt32(0),
|
|
Nome = reader.GetString(1),
|
|
Email = reader.GetString(2),
|
|
CriadoEm = reader.GetDateTime(3)
|
|
});
|
|
}
|
|
|
|
return clients;
|
|
}
|
|
|
|
public async Task AddClientAsync(Cliente c)
|
|
{
|
|
using var connection = new SqliteConnection(_connectionString);
|
|
await connection.OpenAsync();
|
|
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = @"
|
|
INSERT INTO Clientes (Nome, Email, CriadoEm)
|
|
VALUES ($nome, $email, $criadoEm);
|
|
";
|
|
|
|
command.Parameters.AddWithValue("$nome", c.Nome);
|
|
command.Parameters.AddWithValue("$email", c.Email);
|
|
command.Parameters.AddWithValue("$criadoEm", c.CriadoEm);
|
|
|
|
await command.ExecuteNonQueryAsync();
|
|
}
|
|
|
|
public async Task UpdateClientAsync(Cliente c)
|
|
{
|
|
using var connection = new SqliteConnection(_connectionString);
|
|
await connection.OpenAsync();
|
|
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = @"
|
|
UPDATE Clientes
|
|
SET Nome = $nome, Email = $email
|
|
WHERE Id = $id;
|
|
";
|
|
|
|
command.Parameters.AddWithValue("$nome", c.Nome);
|
|
command.Parameters.AddWithValue("$email", c.Email);
|
|
command.Parameters.AddWithValue("$id", c.Id);
|
|
|
|
await command.ExecuteNonQueryAsync();
|
|
}
|
|
|
|
public async Task DeleteClientAsync(int id)
|
|
{
|
|
using var connection = new SqliteConnection(_connectionString);
|
|
await connection.OpenAsync();
|
|
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = "DELETE FROM Clientes WHERE Id = $id;";
|
|
command.Parameters.AddWithValue("$id", id);
|
|
|
|
await command.ExecuteNonQueryAsync();
|
|
}
|
|
}
|
|
}
|