2017-09-26 67 views
1

我有兩個實體(SaleInvoice和SaleInvoiceDetail)具有一對多關係。我添加的這段代碼正在工作,但我想知道從這種導航屬性(在我的SaleInvoiceDetails的案例列表中)更新或刪除值的最佳做法是什麼。這樣做的最好方法是什麼?更新和刪除具有導航屬性的實體的最佳做法

Here is Model designer view

private void bbUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) 
    { 
     var saleInvoiceInDb= _dbContext.SaleInvoices.Find(_id); 
     if (saleInvoiceInDb == null) return; 

     var saleInvoiceDetails = ((IEnumerable) gvSaleInvoiceDetails.DataSource).Cast<SaleInvoiceDetail>().ToList(); 

     using (var context = new ErpDbContext()) 
     { 
      foreach (var saleInvoiceDetail in saleInvoiceDetails) 
      { 
       if (saleInvoiceDetail.Id != 0) 
       { 
        var invoiceDetailInDb = context.SaleInvoiceDetails.Find(saleInvoiceDetail.Id); 
        invoiceDetailInDb = saleInvoiceDetail; 
        invoiceDetailInDb.SaleInvoiceId = saleInvoiceInDb.Id; 
       } 
       else 
       { 
        saleInvoiceDetail.SaleInvoiceId = saleInvoiceInDb.Id; 
        context.SaleInvoiceDetails.Add(saleInvoiceDetail); 
       } 

       context.SaveChanges(); 
      } 

     } 

     saleInvoiceInDb.CompleteDateTime = DateTime.Today; 
     saleInvoiceInDb.ContranctCode = ""; 
     saleInvoiceInDb.DateTimeAdded = DateTime.Now; 
     saleInvoiceInDb.DateTimeUpdated = DateTime.Now; 
     saleInvoiceInDb.DeliveryDateTime = txtDeliveryDate.DateTime; 
     saleInvoiceInDb.DueDateTime = txtDueDateTime.DateTime; 
     saleInvoiceInDb.InvoiceDescription = txtDescription.Text; 
     saleInvoiceInDb.InvoiceToAdress = txtinvoiceToAdress.Text; 
     saleInvoiceInDb.Period = new DateTime(txtPeriod.DateTime.Year, txtPeriod.DateTime.Month, 1); 
     saleInvoiceInDb.SaleType = txtSoType.Text; 
     saleInvoiceInDb.Status = (byte)txtStatus.ItemIndex; 
     saleInvoiceInDb.SupplierId = _supplierId; 
     saleInvoiceInDb.SupplierCode = txtSupplierCode.Text; 
     saleInvoiceInDb.SupplierInvoiceReference = ""; 
     saleInvoiceInDb.TransactionDateTime = txtTransactionDate.DateTime; 
     saleInvoiceInDb.OrderDate = txtOrderDate.DateTime; 
     saleInvoiceInDb.OrderPeriod = new DateTime(txtOrderDate.DateTime.Year, txtOrderDate.DateTime.Month, 1); 
     saleInvoiceInDb.UserAdded = clsUserProfile.US_LOGIN; 
     saleInvoiceInDb.UserUpdated = clsUserProfile.US_LOGIN; 
     _dbContext.SaveChanges(); 
     Messages.Information("Invoice updated successfully"); 
    } 
} 
+0

有一次,一位發言者說,試想一下,如果你去一個醫生'cough'。然後,一年後,你會回來'發燒'。醫生打開你的情況,刪除「咳嗽」並增加「發燒」。換句話說,在某處註冊您的交易... –

回答

0

您將需要另一個內,如果條件做刪除:

if (saleInvoiceDetail.Id != 0) 
{ 
    var invoiceDetailInDb = context.SaleInvoiceDetails.Find(saleInvoiceDetail.Id); 
    if(invoiceDetailInDb == null) DoDelete(); 
    else{ 
     invoiceDetailInDb = saleInvoiceDetail; 
     invoiceDetailInDb.SaleInvoiceId = saleInvoiceInDb.Id; 
    } 
} 
+0

謝謝Amr Elgarhy爲您的答案。您是否在您的項目中進行這種操作?這是最佳做法嗎? – Nurlan

+0

@Nurlan我不認爲這裏有一個最佳實踐,它是基於每個工作流程,所以在你的情況下,我會像你一樣做。如果它正在工作,乾淨的代碼,所以它沒關係。 –

+0

我很困惑有點更新子元素一個實體因爲我已經問過這個問題。非常感謝你 – Nurlan