0

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; }
    }
}
Paul Almond
  • 127
  • 9
  • 3
    The correct implementation is to set the primary key with `on delete cascade` and have the database do the heavy lifting for you. – Zohar Peled May 11 '18 at 20:36
  • You can do the same thing in EF configuration but I agree with Zohar. Let the DB take care of it. – Jonah Kunz May 11 '18 at 21:05
  • Opps, revisiting this question I see I wrote `primary key` where I should have written `foreign key`... Sorry. – Zohar Peled May 12 '18 at 11:39
  • @ZoharPeled I've updated my post with how I am assigning the foreign Key. How do i include on delete cascade here? – Paul Almond May 12 '18 at 15:48
  • 1
    I've no idea how to do it using EF. I can easily guide you how to do it in SQL, but I'm guessing a quick search can also show how to do it using EF - here is [one post on SO](https://stackoverflow.com/questions/9005948/entity-framework-on-delete-cascade) – Zohar Peled May 12 '18 at 16:55
  • @ZoharPeled - Thanks that linked solved my issue – Paul Almond May 14 '18 at 09:11

1 Answers1

0

Correct solution is:

foreach (var m in lineItem.DelegatesList.Where(f=>f.OrderLineId == orderLineId))
        {
          lineItem.DelegatesList.Remove(m);
        }
Paul Almond
  • 127
  • 9