EF Core DateTimeOffset

3.7k Views Asked by At

I am trying to migrate a model using a DateTime property to a DateTimeOffset property.

When creating the migration, I get the following error:

The property 'MyProp' is of type 'DateTimeOffset' 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'.

Why can't the C# type DateTimeOffset be mapped to the SQL Server Type datetimeoffset (Docs)?

Edit: Added Stacktrace

System.InvalidOperationException: The property 'MyProp' is of type 'DateTimeOffset' 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'.
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidatePropertyMapping(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)

Edit added a reproduction

There is a reproduction on GitHub.

1

There are 1 best solutions below

0
El Mac On BEST ANSWER

The issue is obvious, when taking a closer look at the data model. I have changed the type of the property to be DateTimeOffset, but the EF Core type name is fixed using the attribute [Column("CreateDate", TypeName = "datetime")]. This creates an ambiguity.

[Column("CreateDate", TypeName = "datetime")]
[Required]
public DateTimeOffset CreateDate { get; set; }

Reading the exception message confused me a little, because it states that the Type DateTimeOffset is not supported.

The property 'CreateDate' could not be mapped because it is of type 'DateTimeOffset', which is not a supported primitive type or a valid entity type.