5

My EF Core discriminator column is created like this

modelBuilder.Entity<MyClass>()
 .HasDiscriminator<string>("MyDiscriminator")
 .HasValue<SubClass1>(nameof(SubClass1))
 .HasValue<SubClass2>(nameof(SubClass2))
  ... etc. 

The property MyDiscriminator is not defined on MyClass - its added automatically, However the SQL table created has the column MyDisciminator defined as nvarchar(max) The values in the discriminator column can only be from the list defined, i.e. "SubClass1", "SubClass2" etc.

If I attempt to index the discriminator column I get

Msg 1919, Level 16, State 1, Line 29
Column 'MyDiscriminator' in table 'dbo.MyClass' is of a type that is invalid for use as a key column in an index.

Is there any way to define a string discriminator so the max length can be set to something more reasonable - and that can be indexed?

Or if not could there be any pitfalls in changing it manually in the database using something like

ALTER TABLE dbo.MyClass
   ALTER COLUMN MyDiscriminator nvarchar(50)

1 Answer 1

7

HasDiscriminator configures the discriminator CLR (shadow or regular) property name, type and associated values. The corresponding database column name, type, constraints etc. are configured like any other property - with some of the Property builder overloads.

For instance, you could add the following after the code for configuring the discriminator property:

// Set discriminator column type to varchar(50)
modelBuilder.Entity<MyClass>()
    .Property("MyDiscriminator")
    .IsUnicode(false)
    .HasMaxLength(50);

// Create index 
modelBuilder.Entity<MyClass>()
    .HasIndex("MyDiscriminator")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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