我有兩個實體(SaleInvoice和SaleInvoiceDetail)具有一對多關係。我添加的這段代碼正在工作,但我想知道從這種導航屬性(在我的SaleInvoiceDetails的案例列表中)更新或刪除值的最佳做法是什麼。這樣做的最好方法是什麼?更新和刪除具有導航屬性的實體的最佳做法
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");
}
}
有一次,一位發言者說,試想一下,如果你去一個醫生'cough'。然後,一年後,你會回來'發燒'。醫生打開你的情況,刪除「咳嗽」並增加「發燒」。換句話說,在某處註冊您的交易... –