Skip to content

Translation of TimeOnly.FromTimeSpan on SQL Server should be no-op. #34025

@ajcvickers

Description

@ajcvickers

Originally implemented as part of #33678 and found while writing What's New.

Currently, we insert a cast:

context.Set<Animal>().Where(e => timeOnly > TimeOnly.FromTimeSpan(e.TimeSpan))
SELECT [a].[Id], [a].[TimeSpan]
FROM [Animal] AS [a]
WHERE @__timeOnly_0 > CAST([a].[TimeSpan] AS time)

But since the TimeSpan column is mapped to a time column, there doesn't need to be a cast here.

Details
using (var context = new AppDbContext())
{
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();

    context.Add(new Animal());
    
    await context.SaveChangesAsync();
}

using (var context = new AppDbContext())
{
    var timeOnly = TimeOnly.FromDateTime(DateTime.UtcNow);
    var animals = await context.Set<Animal>().Where(e => timeOnly > TimeOnly.FromTimeSpan(e.TimeSpan)).ToListAsync();
}

public class AppDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Data Source=localhost;Database=BuildBlogs;Integrated Security=True;Trust Server Certificate=True;ConnectRetryCount=0")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Animal>();
    }
}

public class Animal
{
    public int Id { get; set; }

    public TimeSpan TimeSpan { get; set; }

    // public required int[] Ints { get; set; }

    // public Owned1 OwnedReference { get; set; } = null!;
    // public List<Owned1> OwnedCollection { get; set; } = null!;
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions