using NewsBlogAbstractions.Models; using NewsBlogAbstractions.WorkAbstractions; using Npgsql; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NewsBlogDatabaseImplementation.WorkImplementation { public class ArticleWork : IArticleWork { public Article? Create(Article article) { using var con = SqlConnection.GetConnection(); con.Open(); using var cmd = new NpgsqlCommand("INSERT INTO article (title, content, publication_date, author_id, category_id) VALUES (@Title, @Content, @Publication_date, @Author_id, @Category_id)", con); cmd.Parameters.AddWithValue("@Title", article.Title); cmd.Parameters.AddWithValue("@Content", article.Content); cmd.Parameters.AddWithValue("@Publication_date", article.PublicationDate); cmd.Parameters.AddWithValue("@Author_id", article.AuthorId == 0 ? DBNull.Value : article.AuthorId); cmd.Parameters.AddWithValue("@Category_id", article.CategoryId == 0 ? DBNull.Value : article.CategoryId); cmd.ExecuteNonQuery(); return article; } public Article? Delete(int id) { var element = Get(id); using var con = SqlConnection.GetConnection(); con.Open(); using var cmd = new NpgsqlCommand($"DELETE FROM article WHERE article_id = {id}", con); cmd.ExecuteNonQuery(); return element; } public Article? Get(int id) { using var con = SqlConnection.GetConnection(); con.Open(); using var cmd = new NpgsqlCommand($"SELECT * FROM article WHERE article_id = {id}", con); using var reader = cmd.ExecuteReader(); if (reader.Read()) { return new Article { Id = reader.GetInt32(0), Title = reader.GetString(1), Content = reader.GetString(2), PublicationDate = reader.GetDateTime(3), AuthorId = !reader.IsDBNull(4) ? reader.GetInt32(4) : 0, CategoryId = !reader.IsDBNull(5) ? reader.GetInt32(5) : 0, }; } return null; } public List
GetAll() { var articles = new List
(); using var con = SqlConnection.GetConnection(); con.Open(); using var cmd = new NpgsqlCommand("SELECT * FROM article order by article_id", con); using var reader = cmd.ExecuteReader(); while (reader.Read()) { articles.Add(new Article { Id = reader.GetInt32(0), Title = reader.GetString(1), Content = reader.GetString(2), PublicationDate = reader.GetDateTime(3), AuthorId = !reader.IsDBNull(4) ? reader.GetInt32(4) : 0, CategoryId = !reader.IsDBNull(5) ? reader.GetInt32(5) : 0, }); } return articles; } public Article? Update(Article article) { using var con = SqlConnection.GetConnection(); con.Open(); using var cmd = new NpgsqlCommand($"UPDATE article SET title = '{article.Title}', content = '{article.Content}', publication_date = '{article.PublicationDate}', author_id = @Author_Id, category_id = @Category_id WHERE article_id = {article.Id}", con); cmd.Parameters.AddWithValue("@Author_Id", article.AuthorId == 0 ? DBNull.Value : article.AuthorId); cmd.Parameters.AddWithValue("@Category_Id", article.CategoryId == 0 ? DBNull.Value : article.CategoryId); cmd.ExecuteNonQuery(); var element = Get(article.Id); return element; } } }