Home > Blockchain >  How to delete an entry in a dependent entity?
How to delete an entry in a dependent entity?

Time:12-28

I have a principal entity AppUser and a dependent 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 its 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?

CodePudding user response:

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);
  • Related