我只是想用EF4代码来解决一些问题。如果我使用TPH,并且我想把一个获救的人改成讲师,或者反过来,我该如何完成这个任务呢。我的POCO课程:
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");
}
}
假设我有一个人:
var person1 = new Person { FirstName = "Bayram", LastName = "Celik" };
context.People.Add(person1);
context.SaveChanges();
以后我想让这个人成为管理员。我该如何做到这一点。
var person = context.People.FirstOrDefault();
Admin test = person as Admin; // wont work
下面将更改HireDate列,但我的discriminator字段PersonCategory仍然是0。所以就EF而言,它仍然不是管理员类型
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");