user3097695
user3097695

Reputation: 1284

Foreign Keys for Inherited class for C# NetCore EF

I have the following classes

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);
         }
     }

The Person table will be created with "Discriminator": "Person" or "Employee". In case after the record in "Skill" table is deleted, we don't want there is a dead reference in the employee object. How do I add a foreign key "SkillId" to the Person table?

Upvotes: 0

Views: 37

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89386

Add a Navigation property on Employee for Skill,

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

and configure the cascading behvior like this:

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

Upvotes: 1

Related Questions