How to delete an entry in a dependant entity?

I have a principal entity AppUser and a dependant entity Account.

The following code shows a one-to-many relationship between them:

public class AppUser : IdentityUser
{
    public ICollection<Account> Accounts { get; set; } = new List<Account>();
}

public class Account
{
    public Guid Id { get; set; }

    public AppUser User { get; set; }

    public string UserId { get; set; }
}

My OnModelCreating method looks like this:

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<Account>()
            .HasOne(x => x.User)
            .WithMany(u => u.Accounts)
            .HasForeignKey(fk => fk.UserId)
            .OnDelete(DeleteBehavior.Cascade);
    }

Now if I have a AppUser object and want to remove one of it’s accounts like

user.Accounts.Remove(account);

this only removes the foreign key reference in that account entry. How can I make sure it fully deletes the entry in the database?

>Solution :

Call Remove on the corresponding DbSet (assuming names of variable and the property):

_context.Accounts.Remove(account);

Also possibly you can consider marking the parent entity as required (see this and this):

builder.Entity<Account>()
    .HasOne(x => x.User)
    .WithMany(u => u.Accounts)
    .HasForeignKey(fk => fk.UserId)
    .IsRequired(true)
    .OnDelete(DeleteBehavior.Cascade);

Leave a Reply