假设我有一些课程:
public class BaseModel
{
[Key]
public int Id { get; set; }
}
public class Person : BaseModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string Email { get; set; }
}
public class Employee : Person
{
public string Position { get; set; }
public decimal Wage { get; set; }
public PaymentType PaymentType { get; set; }
public virtual Company Company { get; set; }
}
目前我有这个:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>().HasRequired(e => e.PaymentType);
modelBuilder.Entity<Employee>().Map(t =>
{
t.MapInheritedProperties();
t.ToTable("Employees");
});
modelBuilder.Entity<Company>().HasMany(c => c.Employees).WithRequired(e => e.Company).Map(t => t.MapKey("Company_Id"));
}
我为Person和Employee获取了两个表,但我不喜欢{Person}表中添加Person属性的MapInheritedProperties()
。
如何使基类(Person)成为外键?
答案 0 :(得分:1)
为了将基类用作没有主键问题的foreing键/导航属性。您需要使用每个类型的表或每个层次结构的表。
在使用该模型的情况下,建模者应该这样做。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>().HasRequired(e => e.PaymentType);
modelBuilder.Entity<Person >().ToTable("Persons");
modelBuilder.Entity<Employee>().ToTable("Employees");
modelBuilder.Entity<Company>().HasMany(c => c.Employees).WithRequired(e => e.Company).Map(t => t.MapKey("Company_Id"));
}
这将创建两个表。在名称上,人员的所有字段和员工的所有字段都有“员工”。两个表都将共享相同的主键
上获得非常详细的解释