我正在尝试将 AdventureWorks 2012 示例数据库映射到 EF 6.1.3 代码优先数据层,但我对如何映射 Employee
感到困惑和 Person
实体。 Employee 显然应该来自 Person
, 与 Person.PersonType
的 EM
, 但我不知道如何使用 EntityTypeConfiguration<TEntity>
来映射它“映射”类。知道这一点,我也可以映射 Person
从 BusinessEntity
派生.
最佳答案
我将解释如何使用 Code First 方法在 Employee
和 Person
表之间执行映射,您可以按照相同的过程在 之间映射继承BusinessEntity
和 Person
。
使用的继承映射策略是 TPT(每个类型的表),我创建了一个简单的控制台应用程序,安装了 AdventureWorks2012 数据库后,我按照 EF DataModel 向导生成代码第一类,我将修改这些类以映射继承,所以这里是结果代码:
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; }
}
员工类:
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; }
}
最后是 AW 上下文类:
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");
}
}
一个简单的测试(对我有用 ;)):
class Program
{
static void Main(string[] args)
{
using(var db= new AW())
{
var e = db.Employees.First();
e.JobTitle = "Web Developper";
db.SaveChanges();
}
}
}
可以引用this文章了解更多详情
关于c# - 如何在 EF 代码优先中映射继承的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29888160/