Delete Records in Entity Framework Core

Delete Records in Entity Framework Core

Entity Framework Core API builds and executes the DELETE statement in the database for the entities whose EntityState is set as Deleted. The method DbContext.Remove() is used for deleting an entity.

Consider the following code which deletes Department with Id ‘3’.

var dept = new Department()
{
    Id = 1002
};

using (var context = new CompanyContext())
{
    context.Remove(dept);
    await context.SaveChangesAsync();
}

Once the Remove() method is called for the department entity, the EF marks the 3rd id’s EntityState as Deleted. So when the SaveChangesAsync() method is called the 3rd department record is deleted from the database.

deleting record ef core
Interesting EF Core tutorial: Configurations in Entity Framework Core

Delete Multiple Records

Use DbContext.RemoveRange() to delete multiple entities in one go. The below codes remove 3 Department records with Id’s as – 1, 2 & 3 in one go.

List<Department> dept = new List<Department>()
{
    new Department(){Id=1},
    new Department(){Id=2},
    new Department(){Id=3}
};

using (var context = new CompanyContext())
{
    context.RemoveRange(dept);
    await context.SaveChangesAsync();
}
If the key value specified in the Remove() or RemoveRange() method does not exist then EF Core will thrown exception of type DbUpdateConcurrencyException.

Delete Related Records

If an entity has relationship with other entities such as one-to-one or one-to-many then deleting related data, when the root entity is deleted, depends on how the relationship is configured.

By using Fluent API of Entity Framework Core you can define referential constraint options. There are of 4 types:

  • Cascade : Related entities are also deleted.
  • ClientSetNull : It is the default value. Here foreign key properties will be set to null.
  • Restrict : Prevents Cascade delete.
  • SetNull : The values of foreign key properties will be set to null.
Setting “Cascade” delete

Open the Database Context File of your application, there set the referential constrains with the OnDelete() method. Inside this OnDelete() method set DeleteBehavior to Cascade. I have marked this with highlighted text in the below given code.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>(entity =>
    {
        entity.Property(e => e.Designation)
            .IsRequired()
            .HasMaxLength(25)
            .IsUnicode(false);

        entity.Property(e => e.Name)
            .IsRequired()
            .HasMaxLength(100)
            .IsUnicode(false);

        entity.HasOne(d => d.Department)
            .WithMany(p => p.Employee)
            .HasForeignKey(d => d.DepartmentId)
            .OnDelete(DeleteBehavior.Cascade)
            .HasConstraintName("FK_Employee_Department");
    });
}

Now when I delete a record in the Department table then all the related records in the Employee table are also deleted automatically.

Check the below code where I am deleting the 5th id department. So all employees that are in the 5th department are also deleted automatically.

using (var context = new CompanyContext())
{
    Department dept = context.Department.Where(a => a.Id == 5).Include(x => x.Employee).FirstOrDefault();
    context.Remove(dept);
    await context.SaveChangesAsync();
}

Download the source code:

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.