Search code examples
c#asp.netentity-frameworkn-tier-architecture

SaveChanges problem in N-Tier Architecture


Normally, with MVC I use db.savechanges() method after I do some processes. But check the below code when I use N-Tier Architecture in everyloop its gonna insert in this way but I dont want it. I have to check all the items first. If there is no problem then I have to insert it all together.

              foreach (var item in mOrderList)
                {
                    MOrder mOrder = new MOrder();
                    mOrder.StatusAdmin = false;
                    mOrder.Date = DateTime.Now;
                    mOrder.StatusMVendor = "Sipariş alındı.";
                    mOrder.HowMany = item.HowMany;
                    mOrder.MBasketId = item.MBasketId;
                    mOrder.MProductId = item.MProductId;
                    mOrder.MVendorId = item.MVendorId;
                    mOrder.WInvestorId = item.WInvestorId;

                    MProduct mprostock = _imProductService.GetMProductById(item.MProductId);
                    if (mprostock.Stock<=0)
                    {
                        return ReturnErrorAndSuccess(HttpStatusCode.NotFound, "MProduct", mprostock.Name + " ürününde stok kalmadığı için işlem tamamlanamadı.");
                    }
                    _imOrderService.InsertMOrder(mOrder);
                }

Solution

  • all you have to do is:

    • first you should define a method that get list of mProductId and then return list of MProduct.

    • after that you should check if there is any record with Stock<=0 then return your error. -also for your insert you should define a method that get list of MOrder and return appropriate datatype for example Boolean.

      public List<MProduct> GetMProductByIds(List<MProductId> mProductId)
      {
        //getting record code
      }
      
      public bool AddMOrder(List<MOrder> mOrder)
      {
        //inserting record code
      }