I will explain how to perform the mapping between the Employee
and the Person
tables using Code First approach, you can follow the same procedure to map inheritance between BusinessEntity
and Person
.
The inheritance mapping strategy used is TPT (Table Per Type), I've created a simple Console Application, With the AdventureWorks2012 Database installed, I followed the EF DataModel Wizard to generate the code first classes that I will modify to map the inheritance, So here is the resulted code:
The Person class:
public partial class Person
{
[Key]
public int BusinessEntityID { get; set; }
[Required]
public string PersonType { get; set; }
public bool NameStyle { get; set; }
public string Title { get; set; }
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
public string Suffix { get; set; }
public int EmailPromotion { get; set; }
[Column(TypeName = "xml")]
public string AdditionalContactInfo { get; set; }
[Column(TypeName = "xml")]
public string Demographics { get; set; }
}
The Employee class:
public partial class Employee: Person
{
[Required]
public string NationalIDNumber { get; set; }
[Required]
public string LoginID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public short? OrganizationLevel { get; set; }
[Required]
public string JobTitle { get; set; }
[Column(TypeName = "date")]
public DateTime BirthDate { get; set; }
[Required]
public string MaritalStatus { get; set; }
[Required]
public string Gender { get; set; }
[Column(TypeName = "date")]
public DateTime HireDate { get; set; }
public bool SalariedFlag { get; set; }
public short VacationHours { get; set; }
public short SickLeaveHours { get; set; }
public bool CurrentFlag { get; set; }
public Guid rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
}
And Finally the AW Context Class:
public partial class AW : DbContext
{
public AW()
: base("name=AWConnectionString")
{
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Person> People { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().ToTable("Person.Person");
modelBuilder.Entity<Employee>().ToTable("HumanResources.Employee");
}
}
A simple test (That works for me ;) ):
class Program
{
static void Main(string[] args)
{
using(var db= new AW())
{
var e = db.Employees.First();
e.JobTitle = "Web Developper";
db.SaveChanges();
}
}
}
You can refer to this article for more details
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…