我试图将AdventureWorks 2012示例数据库映射到EF 6.1.3代码优先数据层,并坚持如何映射Employee
和Person
实体。员工显然应该来自Person
,Person.PersonType
EM
,但我不知道如何使用EntityTypeConfiguration<TEntity>
&#39;映射&#39来映射;类。知道了这一点,我也可以将Person
映射到BusinessEntity
。
答案 0 :(得分:0)
我将解释如何使用Code First方法在Employee
和Person
表之间执行映射,您可以按照相同的过程来映射BusinessEntity
和{{1}之间的继承}}
使用的继承映射策略是TPT(Table Per Type),我创建了一个简单的控制台应用程序,在安装了AdventureWorks2012数据库的情况下,我按照EF DataModel向导生成了代码,我将修改这些代码来映射继承,所以这是结果代码:
Person类:
Person
员工类:
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; }
}
最后是AW上下文类:
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; }
}
一个简单的测试(对我有用;)):
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");
}
}
您可以参考this文章了解更多详情