CardCollectorDatabase.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using CardCollector.DataBase.Entity;
  5. using Microsoft.EntityFrameworkCore;
  6. namespace CardCollector.DataBase
  7. {
  8. using static Resources.AppSettings;
  9. /* Предоставляет доступ к базе данных */
  10. public class CardCollectorDatabase : DbContext
  11. {
  12. /* Скрываем конструктор, чтобы его нельзя было использовать извне */
  13. private CardCollectorDatabase() { }
  14. /* Объект базы данных */
  15. private static CardCollectorDatabase _instance;
  16. /* Предоставляет доступ к объекту */
  17. public static CardCollectorDatabase Instance
  18. {
  19. get
  20. {
  21. if (_instance != null) return _instance;
  22. _instance = new CardCollectorDatabase();
  23. _instance.Database.EnsureCreated();
  24. return _instance;
  25. }
  26. }
  27. private static readonly Dictionary<Type, CardCollectorDatabase> _specificInstances = new ();
  28. public static CardCollectorDatabase GetSpecificInstance(Type type)
  29. {
  30. try
  31. {
  32. return _specificInstances[type];
  33. }
  34. catch (Exception)
  35. {
  36. var newInstance = new CardCollectorDatabase();
  37. _specificInstances.Add(type, newInstance);
  38. newInstance.Database.EnsureCreated();
  39. return newInstance;
  40. }
  41. }
  42. public static async Task SaveAllChangesAsync()
  43. {
  44. try
  45. {
  46. await Instance.SaveChangesAsync();
  47. foreach (var instance in _specificInstances.Values)
  48. await instance.SaveChangesAsync();
  49. } catch (Exception) { /* Ignored */ }
  50. }
  51. /* Таблицы базы данных, представленные Entity объектами */
  52. public DbSet<UserEntity> Users { get; set; }
  53. public DbSet<CashEntity> CashTable { get; set; }
  54. public DbSet<UserStickerRelationEntity> UserStickerRelations { get; set; }
  55. public DbSet<StickerEntity> Stickers { get; set; }
  56. public DbSet<AuctionEntity> Auction { get; set; }
  57. public DbSet<ShopEntity> Shop { get; set; }
  58. public DbSet<DailyTaskEntity> DailyTasks { get; set; }
  59. /* Конфигурация подключения к БД */
  60. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  61. {
  62. optionsBuilder.UseMySQL(
  63. $"server={DB_IP};" +
  64. $"port={DB_PORT};" +
  65. $"database={DB_SCHEMA};" +
  66. $"uid={DB_UID};" +
  67. $"pwd={DB_PWD}"
  68. );
  69. }
  70. }
  71. }