简体   繁体   中英

Deleting Child Entries when deleting parent

I've read around various posts but none seem to match my issue. I need to delete child entries linked to a foreignkey when the parent is deleted.

Currently I have this code:

public async Task UpdateLineItemByOrderLineId(int orderLineId, int newQuantity)
    {
        var clientBasket = await GetBasketAsync();
        var lineItem = clientBasket.OrderLines.FirstOrDefault(x => x.OrderLineId == orderLineId);
        if (newQuantity == 0)
        {
            _orderLinesRepository.Delete(lineItem);
            _orderLinesRepository.Save();
        }

and this linked to the following repository

public class OrderLinesRepository : GenericRepository<OrderLine>, IOrderLinesRepository
    {
        public OrderLinesRepository(IDbContextFactory dbContextFactory)
            : base(dbContextFactory)
        {
        }
    }

Posts seem to mention entity framework etc and being as I'm learning C# from a solution handed to me to bring to completion I don't see matching code that reflects EF.

I don't necessarily need to delete the child elements but simply set the ForeignKey to null. One thing to note is that I can have multiple child entries linked to the ForeignKey.

What is the correct implementation to achieve the above?

Edit: Foreign Key Assignment

    namespace TSW.Ecommerce.Data.Api
{
    public class OrderDelegate
    {
        [Key]
        public int OrderDelegateId { get; set; }
        [ForeignKey("OrderLineId")]
        public virtual OrderLine OrderLine { get; set; }
        public int? OrderLineId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}

Correct solution is:

foreach (var m in lineItem.DelegatesList.Where(f=>f.OrderLineId == orderLineId))
        {
          lineItem.DelegatesList.Remove(m);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM