Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading