Store Enums as Strings in EF Core 6
Asked Answered
S

1

9

While looking for a solution to store all our enums as strings in the database, i came up with the following code.

protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
    builder.Properties(typeof(Enum))
        .HaveConversion<string>()
        .HaveColumnType("nvarchar(128)");
}

Doing some testing, this seems to work just fine, even for nullable enums. The limitation to 128 characters is completely optional, the default is nvarchar(max).

Since all other solutions around this topic require much more and complex code, i would like to know if there are any downsides to my rather simple approach?

Solange answered 11/11, 2021 at 9:44 Comment(2)
All other solutions are for pre EFC 6.0 where this functionality simply does not exist. Once added, why should be there downsides? Moreover that's one of the primary usage scenarios it was added for.Tachyphylaxis
Thanks for clarification @IvanStoev. Would happily accept your comment as answer to my question.Solange
C
0

I think the only concern is if you changed the enum element names then you would get different values in the table and can not be casted back when you select from the table.

I know you are asking about downsides of the solution itself not the requirement but I just wanted to get your eyes on this concern.

A possible solution for that issue is by adding migration scripts to change old values to new values maintaining the data integrity.

Content answered 31/7 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.