Pcc2DbContext.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
  3. using PCC2.Data.Entity;
  4. namespace PCC2.Data
  5. {
  6. public class Pcc2DbContext : DbContext
  7. {
  8. private const string DbFileName = "PCC2.DB3";
  9. public DbSet<Setting> Settings { get; set; } = null!;
  10. public DbSet<LocalPeer> LocalPeers { get; set; } = null!;
  11. public DbSet<RemotePeer> RemotePeers { get; set; } = null!;
  12. public DbSet<ChatRecord> ChatRecords { get; set; } = null!;
  13. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  14. {
  15. optionsBuilder.UseSqlite($"Data Source={DbFileName}");
  16. }
  17. protected override void OnModelCreating(ModelBuilder modelBuilder)
  18. {
  19. base.OnModelCreating(modelBuilder);
  20. // 创建 ValueConverter:将 DateTimeOffset 转换为 UTC 的 yyyyMMddHHmmssfff 格式
  21. var dateTimeOffsetToBigIntConverter = new ValueConverter<DateTimeOffset, long>(
  22. v => long.Parse(v.UtcDateTime.ToString("yyyyMMddHHmmssfff")),
  23. v => DateTimeOffset.ParseExact(v.ToString(), "yyyyMMddHHmmssfff", null, System.Globalization.DateTimeStyles.AssumeUniversal)
  24. );
  25. var nullableDateTimeOffsetToBigIntConverter = new ValueConverter<DateTimeOffset?, long?>(
  26. v => v.HasValue ? long.Parse(v.Value.UtcDateTime.ToString("yyyyMMddHHmmssfff")) : (long?)null,
  27. v => v.HasValue ? DateTimeOffset.ParseExact(v.Value.ToString(), "yyyyMMddHHmmssfff", null, System.Globalization.DateTimeStyles.AssumeUniversal) : (DateTimeOffset?)null
  28. );
  29. // 应用于所有 DateTimeOffset 字段
  30. foreach (var entityType in modelBuilder.Model.GetEntityTypes())
  31. {
  32. foreach (var property in entityType.GetProperties())
  33. {
  34. if (property.ClrType == typeof(DateTimeOffset))
  35. {
  36. property.SetValueConverter(dateTimeOffsetToBigIntConverter);
  37. }
  38. else if (Nullable.GetUnderlyingType(property.ClrType) == typeof(DateTimeOffset))
  39. {
  40. property.SetValueConverter(nullableDateTimeOffsetToBigIntConverter);
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }