Andres
Andres

Reputation: 119

EF6 extending an TPH hierarchy (mixing TPH and TPT)

I have a table used to store several inherited entities in TPH configuration. That works well and there are no issues over that. The issue I'm facing is that I need to extend some of those entities with additional fields and want those new fields stored in its own table using TPT.

To put some context I will give you an example: The TPH stores a root PERIOD class and several inherited ones like QUARTER, MONTH, WEEK, etc, using a discriminator field. So now I need to create a special QUARTER with some additional fields and want to store those additional field in its own table.

Is that possible in EF? I'm using EF 6.1 and haven't found a working sample or explanation on how to accomplish this specific scenario.

Thanks in advance,

Andrés.

Upvotes: 3

Views: 389

Answers (1)

codeworx
codeworx

Reputation: 2745

   public abstract class Period
    {
        public int  Id { get; set; }

        public string DisplayName { get; set; }

    }

    public class Month : Period {
        public byte MonthValue { get; set; }

    }

    public class Quarter : Period {
        public byte QuarterValue { get; set; }

    }

    public class SpecialQuarter : Quarter {
        public int SpecialQuarterValue { get; set; }
    }

    public class TestContext : DbContext {
        public DbSet<Period> Periods { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Period>().ToTable("Period");

            // TPH
            modelBuilder.Entity<Month>().Map(p => p.Requires("PeriodType").HasValue("M"));
            modelBuilder.Entity<Quarter>().Map(p => p.Requires("PeriodType").HasValue("Q"));

            //TPT
            modelBuilder.Entity<SpecialQuarter>().Map(p => p.ToTable("SpecialQuarter"));
        }
    }

This context maps to these tables.

CREATE TABLE [dbo].[Period] (
    [Id] [int] NOT NULL IDENTITY,
    [DisplayName] [nvarchar](max),
    [MonthValue] [tinyint],
    [QuarterValue] [tinyint],
    [PeriodType] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.Period] PRIMARY KEY ([Id])
)
CREATE TABLE [dbo].[SpecialQuarter] (
    [Id] [int] NOT NULL,
    [SpecialQuarterValue] [int] NOT NULL,
    CONSTRAINT [PK_dbo.SpecialQuarter] PRIMARY KEY ([Id])
)

Upvotes: 2

Related Questions