How to create ParentId in Table Per Type (TPT) Inheritance Pattern RRS feed

  • Question

  • I have 4 classes as follows.

    Base Class

    public class KnowledgeDocument


     public int Id {get; set;}

     public string Title {get; set;}

     public string Description {get; set;}


    Derived Classes

    public class LessonsLearnt : KnowledgeDocument


     public string LessonLearntTypeName


    public class BestPractice : KnowledgeDocument



    public class DataContext : DbContext


    public DbSet<KnowledgeDocument> KnowledgeDocuments {get; set;}

    public DbSet<LessonsLearnt> LessonsLearnt{get; set;}

    public DbSet<BestPractice> BestPractices{get; set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)


    modelBuilder.Entity<KnowledgeDocument>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);



    The class structure above created the tables as follows.


    Id (PK, int, not null)

    Title (nvarchar(max), null)

    Description (nvarchar(max), null)


    Id (PK, FK, int, not null)

    LessonLearntTypeName (nvarchar(max), null)


    Id (PK, FK, int, not null)

    I wanted to create 1 more class Idea and inherit from KnowledgeDocument. But, each idea can have a parent idea and the other 2 derived types doesn't have parent. How do I create this new class (Idea).

    Please suggest. Thanks in advance.

    Govind K

    Sunday, September 30, 2018 4:19 PM

All replies

  • Hi Govind Karanam,

    According to your description, it seems that you need a self-referencing model class, like this:

    public class Idea : KnowledgeDocuments
        public long? ParentID { get; set; }
        public virtual Idea Parent { get; set; }
        public virtual ICollection<Idea> Children { get; set; }

    In addition, the following link about Most efficient method of self referencing tree using Entity Framework for your reference.


    Best regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 1, 2018 1:57 AM