私は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列を変更しますが、私の識別子フィールド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");