Web
Analytics
Inheritance in Entity framework with example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Inheritance in EF

Inheritance in entity framework ,it is a way to create relationships between database tables.For example primary key and foreign key relationship.

Types of Inheritance

  1. TPH(Table per Hierarchy)
  2. TPC(Table per concrete)
  3. TPT(Table per Type)

 1. TPH:  It is also called single table inheritance. IT mapped all the classes into different columns of database table.when we insert a record into a class(table fields) another classes field will  have null value and another  field(discriminator column-which is created when database table is created) have name of inserted class.

Entity Framework Inheritance

Note: By Default entity framework support TPH

First Install Entity Framework in current project

install-package entityframework

Note: Don’t  forget of connection string in web.config .

<connectionStrings>

    <add name=”conn” connectionString=”server=.\sqlexpress;database=EFInheritance;integrated security=SSPI” providerName=”System.Data.SqlClient”/>

  </connectionStrings>





Example:TPH

Step 1: Create folder named “DAL”

Step 2: Add Class Student in DAL folder

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace Inheritance_IN_EF.DAL

{

    public class Student

    {

        public int StudentId { get; set; }

        public string Name { get; set; }

        public string Class { get; set; }

    }

    public class StudentLogin: Student

    {

        public string UserName { get; set; }

        public string Password { get; set; }

    }

    public class StudentDetails: Student

    {

        public string ContactNo { get; set; }

        public string Address{ get; set; }

    }

}

 

  • Super class name(student) would be the name of database table which have the column names of Student Logins and StudentDetails in Student Table.
  • A column named “discriminator” would be created in table.
  • Discriminator field value would be actions name of class. i.e whether user insert data into student field only , then discriminator field have value student , if insert into student login then it have value studentlogin.
  • If we want to fetch only studentlogin details then it will return only studentlogin details.

Step 3:

Create DataContext Class in DAL Folder

public class DataContext:DbContext

    {

        public DataContext()

            : base(“conn”)

        {

 

        }

        public DbSet<Student> Students { get; set; }

        public DbSet<StudentLogin> StudentsLogin { get; set; }

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            base.OnModelCreating(modelBuilder);

        }

    }

 

Step 4: Run Commands

Enable-migrations

Add-migration initial

Update-database –verbose

Download Source Code





 

TPC(Table Per Class):

a table will be used for the columns for all mapped base class properties, and additional tables will exist for all concrete classes; the additional tables will be linked by foreign keys to the base table.

In TPC base class(Concrete class) will not be created only two classes will be created Studentlogin and StudentDetails.

Example : Make following changes in previous create example:

Step 1:

public abstract class Student

    {

        [Key]

        public int StudentId { get; set; }

        public string Name { get; set; }

        public string Class { get; set; }

    }

    public class StudentLogin: Student

    {

        public string UserName { get; set; }

        public string Password { get; set; }

    }

    public class StudentDetails: Student

    {

        public string ContactNo { get; set; }

        public string Address{ get; set; }

    }

Note: Student class is now abstract class and studentid is primary key

Step 2:

Changes in Data Context Class

public class DataContext:DbContext

    {

        public DataContext()

            : base(“conn”)

        {

 

        }

 

        public DbSet<StudentLogin> StudentsLogin { get; set; }

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<StudentLogin>().Map(st =>

            {

 

                st.MapInheritedProperties();

                st.ToTable(“StudentLogin”);

            });

            modelBuilder.Entity<StudentDetails>().Map(st =>

            {

 

                st.MapInheritedProperties();

                st.ToTable(“StudentDetails”);

            });

        }

    }

Step 3: Run Commands

Enable-migrations

Add-migration initial

Update-database –verbose

Result : Two tables studentlogin and Student Details will be created and each table would have primary key(StudentId) and other base class field.

Output

 

Download Source Code

TPT(Concrete Table Inheritance or Table Per Concrete Class):one table for each concrete class, each with columns for all mapped properties, either specific or inherited by each class.

Example:

Remove abstract keyword from Student Class

public  class Student

    {

        [Key]

        public int StudentId { get; set; }

        public string Name { get; set; }

        public string Class { get; set; }

    }

    public class StudentLogin: Student

    {

        public string UserName { get; set; }

        public string Password { get; set; }

    }

    public class StudentDetails: Student

    {

        public string ContactNo { get; set; }

        public string Address{ get; set; }

    }

Step 2:

DataContext Class

public class DataContext:DbContext

    {

        public DataContext()

            : base(“conn”)

        {

 

        }

        public DbSet<Student> Students { get; set; }

        public DbSet<StudentLogin> StudentsLogin { get; set; }

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Student>().ToTable(“Student”);

            modelBuilder.Entity<StudentDetails>().ToTable(“StudentDetails”);

            modelBuilder.Entity<StudentLogin>().ToTable(“StudentLogin”);

 

        }

    }

Step 3: Run Commands

Enable-migrations

Add-migration initial

Update-database –verbose

Output

TableParClass_Inheritance

Result: Three Tables will be created and Each Table have studentid as primary key field.