bulletboards/ImageBoardServerApp/Data/Repository/PostsRepository.cs

60 lines
No EOL
1.9 KiB
C#

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)
.Include(post => post.Comments)
.ToListAsync();
}
public static async Task<PostData> getPostByIdAsync(int postId)
{
await using var db = new AppDBContext();
return await db.Posts
.Where(post => post.PostID == postId)
.Include(post => post.Image)
.Include(post => post.Comments)
.FirstOrDefaultAsync();
//return await db.Posts.FirstOrDefaultAsync(post => post.PostID == postId);
}
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;
}
}