Thursday, 9 October 2014

Entity framework code first (Table Per Type inheritance)


As we know for re-usability we use inheritance, an object oriented feature. We create base classes and inherit those in child classes to facilitate code reuse and we don’t have to write again and again. In this post we will also have same kind of methodology. We are going to create a “Person” class and inherit this in to Employee and Student class and we will see how entity framework code first handles this kind of inheritance by default. I’m going to use entity framework version 6.0 and Visual Studio 2013.

So first create a console application.













After adding application, first add entity framework using nuget package manager console.














Now time to create 3 different classes (Person, Employee(inheriting Person),Student(inheriting Person)).

 class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

class Employee : Person
    {
        public string Designation { get; set; }
    }

class Student : Person
    {
        public string Standard { get; set; }
    }

Add database to the application:














Add connection string to App.config file:

<connectionStrings>
    <add connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\tanya.jain\documents\visual studio 2013\Projects\EFCodeFirstExample\EFCodeFirstExample\EFCodeFirstDB.mdf;Integrated Security=True" name="MyConnectionString" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Adding database context file:

    public class DataContext : DbContext
    {
        public DataContext()
            : base("MyConnectionString")
        {
        }
        public IDbSet<Student> Students { get; set; }
        public IDbSet<Employee> Employees { get; set; }
    }

Here 2 dbset properties for Employee, Student. Now write within main().

static void Main(string[] args)
        {
            using (var context = new DataContext())
            {
                var employees = context.Employees.ToList();
                foreach (Employee employee in employees)
                {
                    Console.WriteLine(employee.Id);
                }
            }
            Console.ReadLine();
        }


After all these steps run the application and see magic.
Open mdf file:














Here you can see that it has created two tables for both entities so this called “Table Per Type” inheritance where it created a two tables for each type Customer and Student. In future post we will see “Table per hierarchy” inheritance where we will have a single table for Customers and Students.

Hope you like it. Stay tuned for more!!

No comments:

Post a Comment