Reputation: 18485
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");
}
}
Upvotes: 2
Views: 310
Reputation: 205839
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())
;
Upvotes: 3