dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.8k stars 3.2k forks source link

EF Core 9 generates incorrect compiled models for negative enum sentinel values #35142

Open Atulin opened 3 days ago

Atulin commented 3 days ago

EF Core version: 9.0 Database provider: Npgsql (efcore.pg) Target framework: .NET 9 Operating system: Windows 10 IDE: Rider 2024.3

Configuration:

builder
    .Property(cm => cm.Role)
    .IsRequired()
    .HasDefaultValue(EClubMemberRoles.User)
    .HasSentinel((EClubMemberRoles)(-1));

Compiled model:

var role = runtimeEntityType.AddProperty(
    "Role",
    typeof(EClubMemberRoles),
    propertyInfo: typeof(ClubMember).GetProperty("Role", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
    fieldInfo: typeof(ClubMember).GetField("<Role>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
    valueGenerated: ValueGenerated.OnAdd,
    sentinel: (EClubMemberRoles)-1);
role.AddAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.None);
role.AddAnnotation("Relational:DefaultValue", EClubMemberRoles.User);

As you can see, it omits the parentheses around the -1 which leads to the error.

cincuranet commented 3 days ago

The error is CS0075: To cast a negative value, you must enclose the value in parentheses..