delete item from main list if its empty in C# Entity

In this code I check if Unit stock is empty for the same product Id which I selected, then I can delete product, but if so, I also want to delete Product Group for all products that have the same group Id after ensuring they all are empty. What should I do?

here are my model classes

public int Get(int? id)
{
    JalkahoitolaEntities entities = new JalkahoitolaEntities();
    List<int?> items = (from o in entities.Recieved_ammounts
                        where o.ProductId == id
                        select o.UnitStock).ToList();

    if (items.Sum() == 0 || items.Sum() == null)
    {
        Product ProductToBeRemoved = (from o in entities.Products
                                        where o.ProductId == id
                                        select o).First();
        entities.Products.Remove(ProductToBeRemoved);
        entities.SaveChanges();
    }

    entities.Dispose();
    return 1;
}

1 answer

  • answered 2018-01-14 08:21 Ehsan Ullah Nazir

    If I understood your question correctly, you want to delete ProductGroup then you are missing with deletion of ProductGroup .Update your code to add Deletion logic for ProductGroup as well.

    Retrieve Prodcut to be removed

       Product ProductToBeRemoved = (from o in entities.Products
                                        where o.ProductId == id
                                        select o).First();
        entities.Products.Remove(ProductToBeRemoved);
    

    Delete ProductGroup based on ProductToBeRemoved GroupId

        ProductGroup ProductGroupToBeRemoved = (from o in entities.ProductGroup
                                        where o.GroupId== ProductToBeRemoved .GroupId
                                        select o).First();
        entities.ProductGroup.Remove(ProductGroupToBeRemoved);
    

    Then call the SaveChanges()

    UPDATE : After reading OP's comment.

    You don't need to write multiple queries for this. Try using some thing like

    var prodGroupsToRemove = (from ra in entities.Recieved_ammounts
              join prod  in entities.Products on ra.ProductId  equals prod.ProductId            
              join prodGrp in entities.ProductGroup on prod.GroupId equals prodGrp.GroupID             
              where (ra.UnitStock > 0)
              select new { GroupId = prodGrp.GroupId , ProductId = prod.ProductId}).ToList();
    

    Above query will return a list of GroupsID,ProductId you want to delete.

    Note You need to filter out Products/Group based on result to delete.This might not work simple copy/paste, You may need to update it a bit.