簡體   English   中英

如果項目在C#實體中為空,則從主列表中刪除項目

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

在此代碼中,我檢查所選擇的同一產品ID的單位庫存是否為空,然后可以刪除產品,但是如果是這樣,我還想在確保所有產品具有相同組ID后刪除所有具有相同組ID的產品的產品組。空的。 我該怎么辦?

這是我的模特班

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;
}

如果我理解正確你的問題,你想刪除ProductGroup則您與缺失失蹤ProductGroup .Update你的代碼添加刪除邏輯ProductGroup為好。

檢索要刪除的產品

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

刪除ProductGroup基於ProductToBeRemoved GroupId

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

然后調用SaveChanges()

更新 :閱讀OP的評論后。

您不需要為此編寫多個查詢。 嘗試使用類似

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();

上面的查詢將返回您要刪除的GroupsID,ProductId的列表。

注意您需要根據要刪除的結果過濾掉產品/組。這可能無法簡單地復制/粘貼,您可能需要對其進行一些更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM