Delete Records in Entity Framework Core

Delete Records in Entity Framework Core

EF 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 entity.

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

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

using (var context = new CompanyContext())
{
    context.Department.Remove(dept);
    context.SaveChanges();
}

Once the Remove() method is called for the department entity, the EF marks the 3rd id as Deleted. Finally when the SaveChanges() method is called the 3rd department record is deleted from the database.

deleting record ef core

Delete Multiple Records

Use DbContext.RemoveRange() to delete multiple entities in one go. The below codes remove 3 Department records of Ids – 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.Department.RemoveRange(dept);
    context.SaveChanges();
}

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 deleing related data when the root entity is deleted depends on how the relationship is configured.

By using Fluent API you can define referential constraint options. There are 4 options:

  • Cascade : Related entities are deleted.
  • ClientSetNull: Foreign key properties in the dependent entities will be set to null.
  • Restrict: Prevents Cascade delete.
  • SetNull: The values of foreign key properties in the dependent entities will be set to null.

On the Context file of your application you will see the referential constrains applied with the .OnDelete() method. See the below code:

modelBuilder.Entity<Employee>(entity =>
{
    entity.HasOne(d => d.Department)
        .WithMany(p => p.Employee)
        .HasForeignKey(d => d.DepartmentId)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK_Employee_Department");
});

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

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