Search code examples
entity-frameworkasp.net-coreentity-framework-coreef-code-first

Entity Framework Core 3.0 Many-to-Many for the same table


I am using ef core 3.0 code-first database. I have a table, Status, and I need to create a relationship to itself to list the possible "next status" List<Status> SubsequentStatuses. This is of course to systematically control the workflow of the object.

Using this at face value, it creates a one-to-many relationship and a new StatusId column in the table; however, I need to be able to set a status to be a "SubsequentStatus" to more than one Status.

For example, if there are 4 statuses:

  • New
  • In Work
  • Complete
  • Cancelled

I want to have the following

  • New
    • Subsequent Statuses
      • In Work
      • Cancelled
  • In Work
    • Subsequent Statuses
      • Complete
      • Cancelled
  • Complete
    • None
  • Cancelled
    • None

Notice that "Cancelled" is related to both "New" and "In Work"

Here are the classes and config that I have at this point:

public class EstimateStatus
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<EstimateStatusRel> SubsequentStatuses { get; set; }
}

public class EstimateStatusRel
{
    public int EstimateStatusId { get; set; }
    public EstimateStatus EstimateStatus { get; set; }

    public int SubsequentStatusId { get; set; }
    public EstimateStatus SubsequentStatus { get; set; }
}

public class SapphireContext : DbContext
{    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<EstimateStatusRel>().HasKey(x => new { x.EstimateStatusId, x.SubsequentStatusId });

        modelBuilder.Entity<StatusRel>()
            .HasOne(pt => pt.Status)
            .WithMany(p => p.SubsequentStatuses)
            .HasForeignKey(pt => pt.StatusId);
    }
}

The issue this is creating, is that when Entity Framework is building the migration, it errors out about the multiple cascading delete action, but when I add the NoAction modifier to the modelBuilder fluent API, it still does not clear the error


Solution

  • It ended up being because I didn't specify an OnDelete action

    This is my final config:

        modelBuilder.Entity<EstimateStatusRel>()
                    .HasOne(pt => pt.Status)
                    .WithMany(p => p.SubsequentStatus)
                    .HasForeignKey(pt => pt.EstimateStatusId)
                    .OnDelete(DeleteBehavior.NoAction);