Skip to content

Support sql_variant containing DateOnly as native SQL date without client conversion #3934

@Harald-PH

Description

@Harald-PH

Support sql_variant containing DateOnly as native SQL date without client conversion

Problem

When using a SQL Server column of type sql_variant that stores a date, and the CLR value is a DateOnly, the SqlClient does not treat it as a native SQL date. Instead, it fails or requires manual conversion (e.g., via DateOnly.ToDateTime()).

Example:

public class MyEntity
{
    public int Id { get; set; }
    public object? Value { get; set; } // mapped to sql_variant
}

// EF Core model:
modelBuilder.Entity<MyEntity>()
    .Property(e => e.Value)
    .HasColumnType("sql_variant");

// Insert
var e = new MyEntity { Value = DateOnly.FromDateTime(DateTime.Today) };
context.Add(e);
context.SaveChanges(); // Fails or requires pre-conversion

Although SqlClient supports DateOnly for direct parameters with the latest providers (5.1+), it does not automatically handle sql_variant:

  • EF Core sees the property as object
  • SqlClient does not infer that the underlying variant value is a date
  • Causes runtime exceptions or requires manual conversion to DateTime

Expected Behavior

  • Automatically treat DateOnly as SQL date when assigned to a sql_variant column
  • Convert the value internally to the appropriate SQL type for variant
  • Avoid requiring manual DateOnlyDateTime conversion in application code

This would align sql_variant handling for DateOnly with other CLR types:

CLR Type Current EF / SqlClient behavior
int OK
string OK
DateTime OK
DateOnly ❌ fails for sql_variant

Repro Steps

  1. Create a SQL Server table with a sql_variant column.
  2. Define an EF Core model with the property typed as object?.
  3. Attempt to insert a DateOnly value.
  4. Observe failure or the need to manually convert to DateTime.

Additional Context

  • Current SqlClient versions support DateOnly for non-variant columns
  • sql_variant is a generic SQL type, and automatic type inference is missing
  • This is a limitation, not a crash, but affects EF Core scenarios using flexible variant columns

Labels (suggested)

  • enhancement
  • area/SqlClient
  • needs-investigation

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions