ConfigRepository.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using bitforum.Models;
  2. namespace bitforum.Repository
  3. {
  4. public class ConfigRepository
  5. {
  6. private readonly DefaultDbContext _context;
  7. public ConfigRepository(DefaultDbContext context)
  8. {
  9. _context = context;
  10. }
  11. // 값 추가
  12. public void Add(Config config)
  13. {
  14. _context.Config.Add(config);
  15. _context.SaveChanges();
  16. }
  17. // Key로 값 조회
  18. public Config? GetByKey(string key)
  19. {
  20. return _context.Config.FirstOrDefault(c => c.Key == key);
  21. }
  22. // 모든 값 조회
  23. public Dictionary<string, string> GetAll()
  24. {
  25. return _context.Config.ToList().ToDictionary(c => c.Key, c => c.Value);
  26. }
  27. // Config 갱신
  28. public void Update(Config config)
  29. {
  30. _context.Config.Update(config);
  31. _context.SaveChanges();
  32. }
  33. // Replace 메서드 추가: Key가 존재하면 업데이트, 없으면 추가
  34. public void Replace(Config config)
  35. {
  36. var existingConfig = _context.Config.FirstOrDefault(c => c.Key == config.Key);
  37. // 갱신
  38. if (existingConfig != null)
  39. {
  40. existingConfig.Value = config.Value;
  41. existingConfig.Description = config.Description;
  42. _context.Config.Update(existingConfig);
  43. }
  44. else // 신규 추가
  45. {
  46. Add(config);
  47. }
  48. _context.SaveChanges();
  49. }
  50. // id로 Config 삭제
  51. public void DeleteByID(int id)
  52. {
  53. var config = _context.Config.Find(id);
  54. if (config != null)
  55. {
  56. _context.Config.Remove(config);
  57. _context.SaveChanges();
  58. }
  59. }
  60. // id로 Config 삭제
  61. public void DeleteByKey(string key)
  62. {
  63. var config = _context.Config.FirstOrDefault(c => c.Key == key);
  64. if (config != null)
  65. {
  66. _context.Config.Remove(config);
  67. _context.SaveChanges();
  68. }
  69. }
  70. }
  71. }