using EfDataAdapter.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using System; using System.Linq; namespace EfDataAdapter { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.UseEntityTypeConfiguration(); ApplyUtcDateTimeConverter(modelBuilder); base.OnModelCreating(modelBuilder); } private static void ApplyUtcDateTimeConverter(ModelBuilder modelBuilder) { var dateTimeConverter = new ValueConverter<DateTime, DateTime>(v => v.ToUniversalTime(), v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); var dateTimeNullableConverter = new ValueConverter<DateTime?, DateTime?>(v => v.HasValue ? v.Value.ToUniversalTime() : (DateTime?)null, v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : (DateTime?)null); foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { var properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == typeof(DateTime)); foreach (var property in properties) { modelBuilder.Entity(entityType.Name).Property(property.Name) .HasConversion(dateTimeConverter); } properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == typeof(DateTime?)); foreach (var property in properties) { modelBuilder.Entity(entityType.Name).Property(property.Name) .HasConversion(dateTimeNullableConverter); } } } } } ///////////// using Newtonsoft.Json.Serialization; namespace WebApi { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; }); } } }
435300cookie-checkC# WebAPI Entity framework+JSON UTC-time mapping