Vitalii Nesterenko
Vitalii Nesterenko

Reputation: 45

How to map time(0) to TimeOnly Entity Framework SQL Server 2019?

I'm trying to use the new TimeOnly type of C# but when I come to do my migrations I am having the following issue. I am using SQL Server 2019 the error is.

The property 'PassportOffice.CloseTime' is of type 'DateTime' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

I'm using Entity Framework Core 6. The model is as follows.

public class PassportOffice
{
    public int Id { get; set; }
    [Required]
    public TimeOnly OpenTime { get; set; }
    [Required]
    public TimeOnly CloseTime { get; set; }
}

So I've tried to make TimeOnly converter

public class TimeOnlyConverter : ValueConverter<TimeOnly, DateTime>
{
    public TimeOnlyConverter() : base(
       timeOnly => new DateTime(DateOnly.MinValue.Year, DateOnly.MinValue.Month, DateOnly.MinValue.Day,
            timeOnly.Hour, timeOnly.Minute, timeOnly.Second),
       dateTime => TimeOnly.FromDateTime(dateTime))
   { }
}

And used it in DbContext as follows

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder.Properties<TimeOnly>()
        .HaveConversion<TimeOnlyConverter>()
        .HaveColumnType("time(0)");
}

Did I made a mistake? Or is there any other way to solve the problem?

Upvotes: 4

Views: 2847

Answers (2)

Treker
Treker

Reputation: 398

Why not make a converter from TimeOnly to TimeSpan?

public class TimeOnlyConverter : ValueConverter<TimeOnly, TimeSpan>
{
    public TimeOnlyConverter() : base(
        d => d.ToTimeSpan(),
        d => TimeOnly.FromTimeSpan(d))
    { }
}

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 151

Entity Framework Map CLR type TimeSpan SQL Server type to time

Change the Model Definition as below

public class PassportOffice
    {
        public int Id { get; set; }
        [Required]
        public TimeSpan OpenTime { get; set; }
        [Required]
        public TimeSpan CloseTime { get; set; }
    }

No Need for Converter. it will work as expected

Upvotes: 4

Related Questions