Entity Framework TPT inheritance edit a record in base class table and bind it to subclass table

I've used code first for linking to an existing database via TPT inheritance here in this code i have one base class called Person and 2 subclasses called Student and Teacher and both Student and Teacher class inherit from Person class

public class Person
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

public class Student : Person
        public int? Payment { get; set; }

public class Teacher : Person
        public int Wage { get; set; }

and this is my Context Class

public class PersonContext : DbContext
        public PersonContext()
            : base("TPT")
        public DbSet<Person> Persons { get; set; }
        public DbSet<Student> Students { get; set; }
        public DbSet<Teacher> Teachers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

I've inserted a record with FirstName and LastName and saved it in the Persons table, via adding a simple Person instance to the context. It's because I don't know the type of the person in that time. In another list, operator recognizes the record, and tries to add extra data to it (for example adding Payment for students). What should I do now? If I get that person's record and cast it to Student class and try to update it, I'll get this error:

'TablePerTypeInheritance.Models.Person' does not contain a definition for 'Payment' and no extension method 'Payment' accepting a first argument of type 'TablePerTypeInheritance.Models.Person' could be found (are you missing a using directive or an assembly reference?)


You save a record of the type Person, so it will be always retrieved from the DB as Person.

In C# you can't cast a base class to a derived class. Such operation is invalid.

var person = new Person();
var student = (Student)Person; // doesn't compile

If you want to change the type of the record, you have to create a new object of the desired type.

var person = context.Persons.Find(1);
var student = new Student() {
    FirstName = person.FirstName,
    LastName = pesron.LastName


hi my friend you have to use own sql command to do it.

var id = new SqlParameter("@id", std.StudentId);
var rate = new SqlParameter("@rate", std.Rate);
contex.Database.ExecuteSqlCommand("insert into ExcelentSudents values (@id,@rate)", id, rate);

Need Your Help

How to Dismiss a Storyboard Popover

ios objective-c uipopovercontroller uibarbuttonitem uistoryboard

I've created a popover from a UIBarButtonItem using Xcode Storyboards (so there's no code) like this: