1

I have an entity with two enums and I've set a conversion for these two fields to save the string in the database. But when I generate the migration, EF Core creates one column with nvharchar(max) and the other with nvarchar(450).

public enum FirstType
{
    Indexing,
    Reading,
}
public enum SecondType
{
    ProposalAutomationContent,
    NoticeResumeInteraction,
}
var processTypeConverter = new EnumToStringConverter<ProcessType>();
var aiActionTypeConverter = new EnumToStringConverter<AiActionType>();

modelBuilder
    .Entity<AiTokenUsage>()
    .Property(e => e.ProcessType)
    .HasConversion(processTypeConverter);

modelBuilder
    .Entity<AiTokenUsage>()
    .Property(e => e.ActionType)
    .HasConversion(aiActionTypeConverter);
ActionType = table.Column<string>(type: "nvarchar(max)", nullable: false),
ProcessId = table.Column<long>(type: "bigint", nullable: false),
ProcessType = table.Column<string>(type: "nvarchar(450)", nullable: false)

I tried adding a big enum option to one of the enums but EF Core now generates both columns with nvarchar(450).

How does EF Core decides the column length? And why does it have this behaviour?

1
  • @Charlieface that is a snippet from the efcore snapshot. He is showing the result from migration. Commented Jul 4 at 20:37

1 Answer 1

2

The only reason i can think of is that there is an index defined for this column, see also this comment from the ef core maintainer Arthur Vickers: https://github.com/dotnet/efcore/issues/31167#issuecomment-1625074009

I tested it locally and if i define an index on the enum column, the length is limited to 450, otherwise it is a nvarchar(max).

PS: you can also define the enum conversion shorthand with

modelBuilder
   .Entity<AiTokenUsage>()
   .Property(e => e.ProcessType)
   .HasConversion<string>();
1
  • I also had an index for one of the columns and then added an index for the other. Now that you said, it makes sense
    – lcarvalho
    Commented Jul 4 at 20:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.