【发布时间】:2020-04-03 19:08:35
【问题描述】:
我有以下课程
public class Person {
public int Id {get; set;}
public string Name {get; Set;}
}
public class Employee : Person {
public DateTime StartDate {get; set;}
public int? SkillId {get; Set;}
}
public class Skill {
public int Id { get; set;}
public string Description { get; set;}
}
public class HRContext : DbContext
{
public HRContext()
: base()
{
}
public virtual DbSet<Person> Persons
{
get; set;
}
public virtual DbSet<Employee> Employees
{
get; set;
}
public virtual DbSet<Skill> Skills
{
get; set;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>(entity =>
{
entity.HasKey(e => new
{
e.Id,
})
.HasName("PK_Person");
entity.Property(e => e.Id)
.HasColumnName("ID")
.ValueGeneratedOnAdd();
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(255);
}
modelBuilder.Entity<Skill>(entity =>
{
entity.HasKey(e => new
{
e.Id,
})
.HasName("PK_Skill");
entity.Property(e => e.Id)
.HasColumnName("ID")
.ValueGeneratedOnAdd();
entity.Property(e => e.Description)
.IsRequired()
.HasMaxLength(255);
}
}
将使用“Discriminator”创建 Person 表:“Person”或“Employee”。万一“技能”表中的记录被删除后,我们不希望员工对象中有死引用。如何将外键“SkillId”添加到 Person 表?
【问题讨论】:
标签: c# entity-framework inheritance dbcontext