PIbd-21_Danilov_V.V._SUBD/NewsBlog/NewsBlogDatabaseImplementation/WorkImplementation/CommentWork.cs
Владимир Данилов cb6251ab2b Лаба4
2024-05-19 21:59:55 +04:00

90 lines
2.8 KiB
C#

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 CommentWork : ICommentWork
{
public Comment? Create(Comment comment)
{
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand("INSERT INTO comment (title, content, create_date, article_id) VALUES (@Title, @Content, @Create_date, @Article_id)", con);
cmd.Parameters.AddWithValue("@Title", comment.Title);
cmd.Parameters.AddWithValue("@Content", comment.Content);
cmd.Parameters.AddWithValue("@Create_date", comment.CreateDate);
cmd.Parameters.AddWithValue("@Article_id", comment.ArticleId == 0 ? DBNull.Value : comment.ArticleId);
cmd.ExecuteNonQuery();
return comment;
}
public Comment? Delete(int id)
{
var element = Get(id);
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand($"DELETE FROM comment WHERE comment_id = {id}", con);
cmd.ExecuteNonQuery();
return element;
}
public Comment? Get(int id)
{
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand($"SELECT * FROM comment WHERE comment_id = {id}", con);
using var reader = cmd.ExecuteReader();
if (reader.Read())
{
return new Comment
{
Id = reader.GetInt32(0),
Title = reader.GetString(1),
Content = reader.GetString(2),
CreateDate = reader.GetDateTime(3),
ArticleId = !reader.IsDBNull(4) ? reader.GetInt32(4) : 0,
};
}
return null;
}
public List<Comment> GetAll()
{
var comments = new List<Comment>();
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand("SELECT * FROM comment order by comment_id", con);
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
comments.Add(new Comment
{
Id = reader.GetInt32(0),
Title = reader.GetString(1),
Content = reader.GetString(2),
CreateDate = reader.GetDateTime(3),
ArticleId = !reader.IsDBNull(4) ? reader.GetInt32(4) : 0,
});
}
return comments;
}
public Comment? Update(Comment comment)
{
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand($"UPDATE comment SET title = '{comment.Title}', content = '{comment.Content}', create_date = '{comment.CreateDate}', article_id = @Article_Id WHERE comment_id = {comment.Id}", con);
cmd.Parameters.AddWithValue("@Article_Id", comment.ArticleId == 0 ? DBNull.Value : comment.ArticleId);
cmd.ExecuteNonQuery();
var element = Get(comment.Id);
return element;
}
}
}