C
C#4mo ago
Steel

Many To Many relationship with cascading for both entities

Hello, I'm wanting my many to many relationship to cascade delete when either entity is deleted. My issue is I can only set one to DeleteBehaviour.Cascade at a time without it erroring. If I set both to cascade, it tells me an entity can't have multiple cascade paths. I'd like to be able to delete either Application or User and it auto delete their Followers relationship. Here is my code:
builder.Entity<Application>(ent =>
{
ent.HasMany(u => u.Followers)
.WithMany(a => a.Following)
.UsingEntity<Dictionary<string, object>>("ApplicationFollowers",
j => j
.HasOne<User>()
.WithMany()
.HasForeignKey("UserId")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade),
j => j
.HasOne<Application>()
.WithMany()
.HasForeignKey("ApplicationId")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade) // if set to cascade, it errors, otherwise I can't delete applications without deleting the following first
);
});

// Application.cs
public class Application
{
public Guid Id { get; set; } = Guid.Empty;

public ICollection<User> Followers { get; set; } = new List<User>();
}

// User.cs
public class User : IdentityUser<Guid>
{
public ICollection<Application> Following { get; set; } = new List<Application>();
}
builder.Entity<Application>(ent =>
{
ent.HasMany(u => u.Followers)
.WithMany(a => a.Following)
.UsingEntity<Dictionary<string, object>>("ApplicationFollowers",
j => j
.HasOne<User>()
.WithMany()
.HasForeignKey("UserId")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade),
j => j
.HasOne<Application>()
.WithMany()
.HasForeignKey("ApplicationId")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade) // if set to cascade, it errors, otherwise I can't delete applications without deleting the following first
);
});

// Application.cs
public class Application
{
public Guid Id { get; set; } = Guid.Empty;

public ICollection<User> Followers { get; set; } = new List<User>();
}

// User.cs
public class User : IdentityUser<Guid>
{
public ICollection<Application> Following { get; set; } = new List<Application>();
}
Let me know if you need any more code. Any help is appreciated. Thanks
1 Reply
Steel
SteelOP4mo ago
still need help on this

Did you find this page helpful?