I am trying to figure out something with EF4 Code Only. If i use TPH and i wanted to change a saved Person to Instructor or vice versa, how would i accomplish this. My POCO classes:
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Instructor : Person
{
public DateTime? HireDate { get; set; }
}
public class Student : Person
{
public DateTime? EnrollmentDate { get; set; }
}
public class Admin : Person
{
public DateTime? AdminDate { get; set; }
}
public class PersonConfiguration : EntityConfiguration<Person>
{
public PersonConfiguration()
{
this.HasKey(u => u.PersonId).Property(u => u.PersonId).IsIdentity();
MapHierarchy()
.Case<Person>(p => new
{
p.PersonId,
p.FirstName,
p.LastName,
PersonCategory = 0
})
.Case<Instructor>(i => new
{
i.HireDate,
PersonCategory = 1
})
.Case<Student>(s => new
{
s.EnrollmentDate,
PersonCategory = 2
})
.Case<Admin>(a => new
{
a.AdminDate,
PersonCategory = 3
}).ToTable("Person");
}
}
Lets say i have a person:
var person1 = new Person { FirstName = "Bayram", LastName = "Celik" };
context.People.Add(person1);
context.SaveChanges();
Later on i want to make this person an admin. How would i accomplish this.
var person = context.People.FirstOrDefault();
Admin test = person as Admin; // wont work
following will change the HireDate column but my discriminator field PersonCategory is still 0. So it is still not an Admin type as far as EF concerns
Admin admin = new Admin();
admin.PersonId = person.PersonId;
admin.AdminDate = DateTime.Now;
context.ObjectContext.Detach(person);
context.People.Attach(admin);
var customerEntry = context.ObjectContext.ObjectStateManager.GetObjectStateEntry(admin);
customerEntry.SetModified();
customerEntry.SetModifiedProperty("AdminDate");