.NET Core EF读取MySQL中UTC时间自动转为本地时间问题
解决.NET Core 6 + Pomelo EF Core读取MySQL UTC时间自动转本地时间的问题
问题根源
MySQL的datetime/datetime(6)类型本身不存储时区信息,Pomelo EF Core默认会将读取到的DateTime标记为Unspecified类型,而.NET会自动把Unspecified的DateTime当作系统本地时间处理,导致存储的UTC时间被自动转换。
解决方案
1. 全局配置UTC时间处理
在你的DbContext的OnConfiguring方法中,设置Pomelo的DateTimeHandling为Utc,全局统一将读取的时间处理为UTC:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql( "你的数据库连接字符串", new MySqlServerVersion(new Version(8, 0, 28)), // 替换为你的MySQL版本 options => options.DateTimeHandling = DateTimeHandling.Utc ); }
配置后,所有DateTime类型的属性读取后都会被标记为DateTimeKind.Utc,不会自动转为本地时间。
2. 单独配置指定属性
如果不需要全局修改,仅针对CreationTime这类特定属性处理,可以通过Fluent API在OnModelCreating中配置:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Referral>() .Property(r => r.CreationTime) .HasConversion( // 写入数据库时保持UTC时间不变 v => v, // 读取时将时间标记为UTC类型 v => DateTime.SpecifyKind(v, DateTimeKind.Utc) ); }
3. 改用DateTimeOffset类型
如果业务需要明确时区信息,直接将实体中的CreationTime类型从DateTime改为DateTimeOffset:
public class Referral { public int ReferralId { get; set; } public DateTimeOffset CreationTime { get; set; } // 其他属性... }
DateTimeOffset会保留时区偏移信息,读取后不会自动转换,需要转为本地时间时再手动处理,避免多时区环境下的重复转换问题。
内容的提问来源于stack exchange,提问作者Andy Barzyk
相关产品推荐
相关产品推荐

