【问题标题】:Foreign Keys for Inherited class for C# NetCore EFC# Net Core EF 的继承类的外键
【发布时间】: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


    【解决方案1】:

    在 Employee 上为 Skill 添加一个 Navigation 属性,

    public class Employee : Person
    {
        public DateTime StartDate { get; set; }
        public int? SkillId { get; set; }
        public Skill Skill { get; set; }
    }
    

    并像这样配置级联行为:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>()
                        .HasOne(nameof(Employee.Skill))
                        .WithMany()
                        .OnDelete(DeleteBehavior.SetNull);
        }
    

    【讨论】:

    • 当我使用“添加迁移”创建迁移文件时,文件不包含迁移操作。我需要在上面的代码中添加外键定义吗?
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2023-03-31
    • 2013-08-14
    • 2018-11-18
    • 2022-11-17
    • 2023-02-04
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多