1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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<Setting> Settings { get; set; } = null!;
- public DbSet<LocalPeer> LocalPeers { get; set; } = null!;
- public DbSet<RemotePeer> RemotePeers { get; set; } = null!;
- public DbSet<ChatRecord> 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<DateTimeOffset, long>(
- v => long.Parse(v.UtcDateTime.ToString("yyyyMMddHHmmssfff")),
- v => DateTimeOffset.ParseExact(v.ToString(), "yyyyMMddHHmmssfff", null, System.Globalization.DateTimeStyles.AssumeUniversal)
- );
- var nullableDateTimeOffsetToBigIntConverter = new ValueConverter<DateTimeOffset?, long?>(
- 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);
- }
- }
- }
- }
- }
- }
|