Search code examples
linqentity-framework-6datacontextsavechanges

SaveChanges() only affects one row


I want to delete some records and I tried using the following code:

if (objDetail != null) 
{
    objContext.DetailVouchers.RemoveRange(
        objContext.DetailVouchers.Where(t => t.REFNO == strRefNo));
    objContext.SaveChanges();
}

But it only deleted the last record and not all of them.

My Context Class is

class MainContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);

            Database.SetInitializer<MainContext>(null);

        modelBuilder.Entity<MainVoucher>().ToTable("TBL_ACC_VOUCHER_MAIN");
        modelBuilder.Entity<MainVoucher>().HasKey(t => new { t.REFNO });

        modelBuilder.Entity<DetailVoucher>().ToTable("TBL_ACC_VOUCHER_DETAIL");
        modelBuilder.Entity<DetailVoucher>().HasKey(t => new { t.REFNO });
}
}

and create context class object like

MainContext objContext = new MainContext();

Solution

  • You have to make your list of items to delete before using RemoveRange. try reza's solution with ToList() on the first line :

    var items = objContext.DetailVouchers.Where(t => t.REFNO == strRefNo).ToList();
    objContext.DetailVouchers.RemoveRange(items);
    context.SaveChanges();