Newsbot.Collector/Newsbot.Collector.Database/Repositories/IconsTable.cs

65 lines
1.8 KiB
C#
Raw Normal View History

using System.Data;
using Dapper;
using Microsoft.Extensions.Configuration;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Domain.Models;
using Npgsql;
namespace Newsbot.Collector.Database.Repositories;
public class IconsTable : IIconsRepository
{
private readonly string _connectionString;
public IconsTable(string connectionString)
{
_connectionString = connectionString;
}
public IconsTable(IConfiguration configuration)
{
var connstr = configuration.GetConnectionString("database");
if (connstr is null) connstr = "";
_connectionString = connstr;
}
public void New(IconModel model)
{
model.Id = Guid.NewGuid();
using var conn = OpenConnection(_connectionString);
var q = @"Insert Into icons (id, filename, site, sourceid) values (@Id,@FileName, @Site, @SourceId)";
conn.Execute(q, model);
}
public IconModel GetById(Guid id)
{
using var conn = OpenConnection(_connectionString);
var query = "Select * From icons where ID = @id Limit 1;";
var res = conn.Query<IconModel>(query, new
{
id
});
if (!res.Any()) return new IconModel();
return res.First();
}
public IconModel GetBySourceId(Guid id)
{
using var conn = OpenConnection(_connectionString);
var query = "Select * From icons where sourceid = @id Limit 1;";
var res = conn.Query<IconModel>(query, new
{
id
});
if (!res.Any()) return new IconModel();
return res.First();
}
private IDbConnection OpenConnection(string connectionString)
{
var conn = new NpgsqlConnection(_connectionString);
conn.Open();
return conn;
}
}