Delete Related Data in EF Core

asp.net-core ef-core-2.0 entity-framework-core

Question

Two entities with one to many relationship such that a voucher has many voucher details, the problem is when removing one item from the collection of the related data (voucher details) and then saving the changes the entity is not removed from the related table

The delete procedure looks like:

    var voucher = await _voucherRepository.GetCompleteVoucherAsync(Id);
    var item = voucher.VoucherDetails.FirstOrDefault();
    voucher.VoucherDetails.Remove(item);
    _dbContext.Update(voucher);    
    await _dbContext.SaveChangesAsync();

And the Model looks like:

 public class Voucher : BaseEntity
 { 
        public int Id {get; set;}
        -----
        public ICollection<VoucherDetail> VoucherDetails { get; set; }
 }

 public class VoucherDetail : BaseEntity
 {
        public int Id {get; set;}
        -----
        public int VoucherId { get; set; }
        public Voucher Voucher { get; set; }
 }

and here is the context:

builder.HasOne(i => i.Voucher)
           .WithMany(i => i.VoucherDetails)
           .IsRequired().HasForeignKey(i => i.VoucherId)
           .OnDelete(DeleteBehavior.Cascade);

Repository:

public async Task<Voucher> GetCompleteVoucherAsync(int id)
        {
            return await _dbContext.Vouchers
            .Include(i => i.VoucherSource)
            .Include(i => i.VoucherDetails)
            .ThenInclude(i => i.Assets)
            .SingleOrDefaultAsync(s => s.Id == id);
        }

With the above setup insert and update procedures are working perfectly for both the Voucher and/or the VoucherDetails entities only by updating the voucher entity directly. but removing an item from the Voucher Details collection does not seem to trigger a delete statement against the Voucher details entity.

is there anything else that I'm missing?

Edit Edited to show the implementation for the GetCompleteVoucherAsync method

1
2
7/8/2019 11:41:36 AM

Accepted Answer

The issue is that you are just removing the item from the VoucherDetails collection on the voucher object. This is not the same as triggering EF to delete the item from the DBSet.

Change the following line:

voucher.VoucherDetails.Remove(item);

To this line:

_dbcontext.VoucherDetail.Remove(item);
1
7/8/2019 8:29:03 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow