0

I want to create a user relationship table in ASP.NET Core and encounter some problems. If I have to disable cascade delete because of this, how do I prevent orphans?

Error:

Introducing FOREIGN KEY constraint 'FK_UserRelationships_AspNetUsers_User2Id' on table 'UserRelationships' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<UserRelationship>().HasKey(x => new { x.User1Id, x.User2Id });
    }

    public DbSet<UserRelationship> UserRelationships { get; set; }
}

My current model:

public class UserRelationship
{
    public byte RelationshipType { get; set; }
    public ApplicationUser User1 { get; set; }
    public string User1Id { get; set; }
    public ApplicationUser User2 { get; set; }
    public string User2Id { get; set; }
}
Zack
  • 3,799
  • 2
  • 11
  • 12

1 Answers1

0

You have your ApplicationUsers as required so EF will cascade the delete by default twice to the same class (see here).

You need to tell it not to:

builder.Entity<UserRelationship>().HasOne(ur => ur.User1).WithMany().HasForeignKey(ur => ur.UserId1).WillCascadeOnDelete(false);

builder.Entity<UserRelationship>().HasOne(ur => ur.User2).WithMany().HasForeignKey(ur => ur.UserId2).WillCascadeOnDelete(false);
Steve Greene
  • 12,029
  • 1
  • 33
  • 54
  • There is not a method named HasRequired(). Do I miss something? – Zack Aug 10 '17 at 22:15
  • If I disable cascade delete, how do I prevent orphans? – Zack Aug 11 '17 at 04:26
  • Sorry, didn't realize it was EF Core. See [here](https://learn.microsoft.com/en-us/ef/core/modeling/relationships). When you delete a UserRelationship I assume you don't want to delete the Users. If you delete a User, you can check for existing relationship records and delete those first (see [here](https://stackoverflow.com/questions/16565078/delete-parent-with-children-in-one-to-many-relationship)). – Steve Greene Aug 11 '17 at 14:38
  • 1
    It won't cause orphans, it will just block you from deleting. Then you manually deal with referenced entities before deleting principal. – Smit Aug 11 '17 at 22:41