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.
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 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:
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:
Share this article -