Allow underlying type to be used for HasDefaultValue when the property is an enum
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
I had a table [Plu]
```sql
USE [FPSDI771]
GO
/****** Object: Table [dbo].[Plu] Script Date: 2023/12/7 下午 01:43:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Plu](
[PluCode] [bigint] NOT NULL,
[CommName] [nvarchar](64) NOT NULL,
[CustomDate1Flag] [int] NOT NULL,
CONSTRAINT [PK_Plu_1] PRIMARY KEY CLUSTERED
(
[PluCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Plu] ADD CONSTRAINT [DF_Plu_CommName] DEFAULT ('') FOR [CommName]
GO
ALTER TABLE [dbo].[Plu] ADD CONSTRAINT [DF_Plu_CustomDate1Flag] DEFAULT ((1)) FOR [CustomDate1Flag]
GO
```
I have the following C# code:
```C#
public Plu
{
public long PluCode { get; set; }
public string CommName { get; set; }
public EDateIsPrintFlag CustomDate1Flag { get; set; }
}
[JsonConverter(typeof(JsonNumberEnumConverter))]
public enum EDateIsPrintFlag
{
NotPrint = 0,
Print = 1,
}
```

I am using the Entity Framework Core to scaffold my database context. The command I use is:
```bat
dotnet tool update --global dotnet-ef
dotnet ef dbcontext scaffold "Data Source=/*connectionstring*/" "Microsoft.EntityFrameworkCore.SqlServer" -o ./EntityModels -c EFCoreContext --context-dir DataContexts -f --data-annotations --project FPS2_Desktop.DB --no-onconfiguring
```
With EF Core version 8.0.0, the generated code is:
```C#
modelBuilder.Entity(entity =>
{
entity.HasKey(e => e.PluCode).HasName("PK_Plu_1");
entity.Property(e => e.PluCode).ValueGeneratedNever();
entity.Property(e => e.CommName).HasDefaultValue("");
entity.Property(e => e.CustomDate1Flag).HasDefaultValue(1);
});
```
However, this results in an error:
```
System.InvalidOperationException: 'Cannot set default value '1' of type 'System.Int32' on property 'CustomDate1Flag' of type 'Project.Enums.EDateIsPrintFlag' in entity type 'A'.'
```
EF Core version: 8.0.0
Previously, with an older version of EF Core, the generated code was:
(7.0.14)
```C#
modelBuilder.Entity(entity =>
{
entity.HasKey(e => e.PluCode).HasName("PK_Plu_1");
entity.Property(e => e.PluCode).ValueGeneratedNever();
entity.Property(e => e.CommName).HasDefaultValueSql("('')");
entity.Property(e => e.CustomDate1Flag).HasDefaultValueSql("((1))");
});
```
But this approach no longer works after upgrading to version 8.0.0. Can you help me correct this?
EF Core version: 8.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8
Operating system: Win11
IDE: Visual Studio 2022 17.8.2
Contributor guide
Assessment
This issue has not been assessed yet.