I want to implement Cascade on delete functionality for asp.net core boilerplate. But I am unable to do so? Here is what I have done to do this.
Company is the parent Class:
public class Company:FullAuditedEntity<long>
{
public string CompanyName { get; set; }
public string EmployeesCount { get; set; }
public virtual ICollection<Employees> Employees { get; set; }
}
Employee is the Child Class which is having one to many relationship with the Company class.
public class Employees:FullAuditedEntity<long>
{
public string EmployeeName { get; set; }
public string Salaray { get; set; }
[ForeignKey("Company")]
public long CompanyId { get; set; }
public virtual Company Company { get; set; }
}
Here is what I have done in the Dbcontext class to implement Cascade on Delete functionality.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employees>()
.HasOne(e => e.Company)
.WithOne()
.OnDelete(DeleteBehavior.Cascade).HasForeignKey<Employees>(t=>t.CompanyId);
}
But when I delete a record for the parent entity(Company) the relevant record from the child table(Employee) is not deleted.