using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PCC2.Data.Entity; namespace PCC2.Data { public class Pcc2DbContext : DbContext { private const string DbFileName = "PCC2.DB3"; public DbSet Settings { get; set; } = null!; public DbSet LocalPeers { get; set; } = null!; public DbSet RemotePeers { get; set; } = null!; public DbSet ChatRecords { get; set; } = null!; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite($"Data Source={DbFileName}"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 创建 ValueConverter:将 DateTimeOffset 转换为 UTC 的 yyyyMMddHHmmssfff 格式 var dateTimeOffsetToBigIntConverter = new ValueConverter( v => long.Parse(v.UtcDateTime.ToString("yyyyMMddHHmmssfff")), v => DateTimeOffset.ParseExact(v.ToString(), "yyyyMMddHHmmssfff", null, System.Globalization.DateTimeStyles.AssumeUniversal) ); var nullableDateTimeOffsetToBigIntConverter = new ValueConverter( v => v.HasValue ? long.Parse(v.Value.UtcDateTime.ToString("yyyyMMddHHmmssfff")) : (long?)null, v => v.HasValue ? DateTimeOffset.ParseExact(v.Value.ToString(), "yyyyMMddHHmmssfff", null, System.Globalization.DateTimeStyles.AssumeUniversal) : (DateTimeOffset?)null ); // 应用于所有 DateTimeOffset 字段 foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { if (property.ClrType == typeof(DateTimeOffset)) { property.SetValueConverter(dateTimeOffsetToBigIntConverter); } else if (Nullable.GetUnderlyingType(property.ClrType) == typeof(DateTimeOffset)) { property.SetValueConverter(nullableDateTimeOffsetToBigIntConverter); } } } } } }