实体框架仅保存列表中的单个记录

时间:2019-03-31 08:53:20

标签: c# entity-framework entity-framework-core

我正在尝试从TPOSTransactionTPOSTransactionDetail插入新记录

下面的代码来自我班上的一个事件:

_posTransaction = new TPostransaction();
_posTransactionDetail = new TPostransactionDetail();
_posTransactionDetails = new List<TPostransactionDetail>();

_posTransaction.UserId = _user.Id;
_posTransaction.Total = Convert.ToDecimal(txtOrderTotal.Text);
_posTransaction.ChangeDue = Convert.ToDecimal(txtChangeDue.Text);
_posTransaction.AmountPaid = Convert.ToDecimal(txtAmountPaid.Text);
_posTransaction.TransactionDate = DateTime.Now;

foreach (ListViewItem orders in lvOrders.Items)
{
   _posTransactionDetail.ItemId = Convert.ToInt32(orders.SubItems[1].Text);
   _posTransactionDetail.Quantity = Convert.ToInt32(orders.SubItems[3].Text);
   _posTransactionDetail.Subtotal = Convert.ToDecimal(orders.SubItems[4].Text) * Convert.ToDecimal(orders.SubItems[3].Text);
   _posTransactionDetails.Add(_posTransactionDetail);
}

    _posTransaction.TPostransactionDetail = _posTransactionDetails;
    _pos.Add(_posTransaction); //method from a class

这是我保存记录的地方:

当我尝试调试时,POSTransaction.TposTransactionDetail有2条记录,因为这是我从列表中添加的

//this is my primary concern
var posTransaction = dbContext.TPostransaction.Add(POSTransaction);
dbContext.TPostransactionDetail.AddRange(POSTransaction.TposTransactionDetail);
dbContext.SaveChanges();

这将保存TPosTransaction和TPosTransactionDetail的记录,但是正在保存的详细信息仅是一个,而不是2。我尝试删除了AddRange部分,它仍然在我的TposTransactionDetail中保存了一条记录

1 个答案:

答案 0 :(得分:0)

您每次需要创建TPostransactionDetail的新实例时,只需在代码顶部重用该实例即可。