CodexBloom - Programming Q&A Platform

Entity Framework Core 7.0 - Type 'DateTime' not mapping correctly to SQL Server as 'datetime2'

πŸ‘€ Views: 435 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
Entity Framework Core SQL Server datetime2 ASP.NET Core C#

I'm currently using Entity Framework Core 7.0 with a SQL Server 2019 database, and I'm encountering an issue where my `DateTime` properties are not being mapped to the SQL `datetime2` type as expected. Instead, they are getting mapped to `datetime`, which is leading to unexpected truncation of milliseconds in my timestamps. Here’s a simplified version of my entity model: ```csharp public class Event { public int Id { get; set; } public string Name { get; set; } public DateTime EventDate { get; set; } } ``` In my `DbContext`, I’m using the following configuration: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Event>(entity => { entity.Property(e => e.EventDate) .HasColumnType("datetime2"); // Explicitly specify datetime2 }); } ``` I have tried the above configuration, but when I run the migrations and check the database schema, I still see that the `EventDate` column is created with type `datetime`. I used the following command to apply the migrations: ```bash dotnet ef migrations add UpdateEventDate dotnet ef database update ``` Additionally, I have verified that my SQL Server connection string is correct and is targeting the right database. Here's the connection string I've used: ```json "ConnectionStrings": { "DefaultConnection": "Server=myServer;Database=myDb;User Id=myUser;Password=myPassword;" } ``` If I directly run a manual migration script to change the column type to `datetime2`, it works fine, but I would like to automate this through EF Core. Is there a specific reason why EF Core is defaulting to `datetime` for `DateTime` properties, and how can I enforce the correct mapping without manually altering the schema?