bulletboards/ImageBoardServerApp/Data/Repository/PostsRepository.cs

85 lines
2.7 KiB
C#
Raw Permalink 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();
}
2023-01-18 12:56:24 +00:00
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();
}
2023-01-18 12:56:24 +00:00
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)
.FirstOrDefaultAsync();
//return await db.Posts.FirstOrDefaultAsync(post => post.PostID == postId);
}
public static async Task<PostData> getPostByGETAsync(string board, int get)
{
await using var db = new AppDBContext();
return await db.Posts
.Where(post => post.GET == get)
.Where(post => post.Board == board)
.Include(post => post.Image)
.Include(post => post.Comments)
.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;
}
2023-01-18 12:56:24 +00:00
return -1;
}
public static async Task deletePostsFromUser(UserData u)
{
await using var db = new AppDBContext();
var l = db.Posts
.Where(x => x.UserID == u.UserID);
foreach (var e in l)
db.Remove(e);
}
2023-01-18 12:56:24 +00:00
public static async Task<bool> updatePostAsync(PostData postToUpdate)
{
await using var db = new AppDBContext();
db.Posts.Update(postToUpdate);
return await db.SaveChangesAsync() >= 1;
}
2023-01-18 12:56:24 +00:00
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;
}
}