Reputation: 115
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
Upvotes: 8
Views: 11671
Reputation: 4673
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);
Upvotes: 3