DbAccess.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using Microsoft.EntityFrameworkCore;
  2. using PCC.Common.AssemblyInject.Interfaces;
  3. using PCC.DbEntity;
  4. namespace PCC.IO;
  5. internal class DbAccess : IAssemblyInjectSingleton
  6. {
  7. public DbAccess(ILogger<DbAccess> logger)
  8. {
  9. logger.LogInformation($"Init: Create DbContext Instance...");
  10. using var db = new PccDbContext();
  11. logger.LogInformation($"Init: Call CanConnect() ...");
  12. if (db.Database.CanConnect() == false)
  13. {
  14. logger.LogInformation($"Init: Creating Database...");
  15. db.Database.EnsureCreated();
  16. logger.LogInformation($"Creating Database: OK");
  17. }
  18. else
  19. {
  20. logger.LogInformation($"Init: OK");
  21. }
  22. }
  23. public int ChatRecordCreate(ChatRecord entity)
  24. {
  25. using var db = new PccDbContext();
  26. db.ChatRecords.Add(entity);
  27. db.SaveChanges();
  28. return entity.Id;
  29. }
  30. public void ChatRecordUpdateAckTimestamp(int id, DateTimeOffset ackSenderTimestamp)
  31. {
  32. using var db = new PccDbContext();
  33. var ur = new ChatRecord { Id = id, AckTimestamp = DateTimeOffset.Now };
  34. db.Attach(ur);
  35. db.Entry(ur).Property(p => p.AckTimestamp).IsModified = true;
  36. db.SaveChanges();
  37. }
  38. }