转换类:
public class UtcDbDataReader : DbDataReader { private readonly DbDataReader source; public UtcDbDataReader(DbDataReader source) { this.source = source; } public override DateTime GetDateTime(int ordinal) { return DateTime.SpecifyKind(source.GetDateTime(ordinal), DateTimeKind.Utc); } // you need to fill all overrides. Just call the same method on source in all cases public new void Dispose() { source.Dispose(); } public new IDataReader GetData(int ordinal) { return source.GetData(ordinal); } }
定义检查类,这个就是在实体和数据库映射时候提供的AOP编程接口
public class UtcInterceptor : DbCommandInterceptor { public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { base.ReaderExecuted(command, interceptionContext); if (interceptionContext?.Result != null && !(interceptionContext.Result is UtcDbDataReader)) { interceptionContext.Result = new UtcDbDataReader(interceptionContext.Result); } } }
将检查类处理为可配置:
internal class MyDbConfiguration : DbConfiguration { protected internal MyDbConfiguration () { AddInterceptor(new UtcInterceptor()); } }
最后配置给数据库上下文:
[DbConfigurationType(typeof(MyDbConfiguration ))] internal class MyDbContext : DbContext { // ... }
这个我目前还没测试过,只是提供思路,有兴趣的可以自己实践。