Is it possible to rename or configure the discriminator column when using iheritance in Entity Framework?

entity-framework-6

Question

I have a database with a table that contains the column of my POCO class

public class TypeOf
{
    [Key, Column(Order = 0)]
    public string Type { get; set; }

    [Key, Column(Order = 1)]
    public string Key { get; set; }

    public string Value { get; set; }
}

This table already contains a lot of data

HsCode | HP | 4821 1000
SubCode | 423 | T21
SubCode | 022 | 5XL
ProductionLine | X1 | Line one
ProductionLine | X2 | Line two
Country | CN | China
Country | IN | India
…

I would like to improve this by creating inheritance system of TypeOf

public class Country : TypeOf { }
public class ProductionLine : TypeOf { }
public class SubCode : TypeOf { }
public class HsCode : TypeOf { }

By using the "Type" column as discriminator.

At this moment when I start to use the inheritance the db migration still want to use a Discriminator column.

public partial class TypeOf : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.TypeOfs", "Discriminator", c => c.String(nullable: false, maxLength: 128));
    }

    public override void Down()
    {
        DropColumn("dbo.TypeOfs", "Discriminator");
    }
}
1
1
11/22/2018 10:14:42 AM

Popular Answer

It's possible, although not so intuitive (IMHO, for EF designers it might seem logical and obvious).

You need to use Map fluent API and repeat Requires(e => e.Type).HasValue() for all derived types (and also the base type if it is not abstract).

For the sample model from the post it should be:

modelBuilder.Entity<TypeOf>()
    .Map(m => m.Requires(e => e.Type).HasValue())
    .Map<Country>(m => m.Requires(e => e.Type).HasValue())
    .Map<ProductionLine>(m => m.Requires(e => e.Type).HasValue())
    .Map<SubCode>(m => m.Requires(e => e.Type).HasValue())
    .Map<HsCode>(m => m.Requires(e => e.Type).HasValue())
    ;
1
11/22/2018 10:10:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow