bulletboards/ImageBoardServerApp/Data/Repository/PostsRepository.cs

62 lines
2 KiB
C#
Raw Normal View History

2023-01-18 12:56:24 +00:00
using Microsoft.EntityFrameworkCore;
namespace ImageBoardServerApp.Data.Repository;
public static class PostsRepository
{
public static async Task<List<PostData>> getPostsAsync()
{
await using var db = new AppDBContext();
return await db.Posts.ToListAsync();
}
public static async Task<List<PostData>> getPostsByBoardAsync(string board)
{
await using var db = new AppDBContext();
return await db.Posts
.Where(post => post.Board.Equals(board))
.Include(post => post.Image)
2023-01-25 16:26:21 +00:00
.Include(post => post.Comments)
2023-02-03 10:33:56 +00:00
.Include(post => post.User)
2023-01-18 12:56:24 +00:00
.ToListAsync();
}
public static async Task<PostData> getPostByIdAsync(int postId)
{
await using var db = new AppDBContext();
2023-01-25 22:45:36 +00:00
return await db.Posts
.Where(post => post.PostID == postId)
.Include(post => post.Image)
.Include(post => post.Comments)
2023-02-03 10:33:56 +00:00
.Include(post => post.User)
2023-01-25 22:45:36 +00:00
.FirstOrDefaultAsync();
//return await db.Posts.FirstOrDefaultAsync(post => post.PostID == postId);
2023-01-18 12:56:24 +00:00
}
public static async Task<int> createPostAsync(PostData postToCreate)
{
await using var db = new AppDBContext();
await db.Posts.AddAsync(postToCreate);
if (await db.SaveChangesAsync() >= 1)
{
Console.WriteLine($"Created post with ID: {postToCreate.PostID}");
return postToCreate.PostID;
}
return -1;
}
public static async Task<bool> updatePostAsync(PostData postToUpdate)
{
await using var db = new AppDBContext();
db.Posts.Update(postToUpdate);
return await db.SaveChangesAsync() >= 1;
}
public static async Task<bool> deletePostAsync(int postId)
{
await using var db = new AppDBContext();
PostData postToDelete = await getPostByIdAsync(postId);
db.Remove(postToDelete);
return await db.SaveChangesAsync() >= 1;
}
}