仅在实体框架和窗口窗体中保存第一行

本文关键字:一行 保存 实体 框架 窗体 窗口 | 更新日期: 2023-09-27 18:35:25

在Windows表单应用程序中,我有2个类,我使用的是实体框架6。

public class Sale
{
    public Sale()
    {
        SalesDetails = new List<SalesDetail>();
    }
    [Key]
    public int SaleId { get; set; }
    public DateTime DateAdded { get; set; }
    public decimal Total { get; set; }
    public decimal Discount { get; set; }
    public decimal FinalTotal { get; set; }
    public virtual ICollection<SalesDetail> SalesDetails { get; set; }
}
public class SalesDetail
{
    [Key]
    public int SaleDetailsId { get; set; }
    public int ProductId { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal TotalPrice { get; set; }
    public virtual Sale Sales { get; set; }
}

DbContext是:

public class MyStoreDbContext:DbContext
{
    public IDbSet<Sale> Sales { get; set; }
    public IDbSet<SalesDetail> SalesDetails { get; set; }
}

我尝试通过每次循环数据网格视图和项目来将SalesDetail列表保存到Sale实体,尽管销售详细信息具有行列表我的代码是

    private void btnSave_Click(object sender, EventArgs e)
    {
        if (txtBarcode.Text != "")
        {
            // prepare items data
            Sale newSale = new Sale();
            SalesDetail sl = new SalesDetail();
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                sl.Quantity = int.Parse(grdItems.Rows[i].Cells["Quantity"].Value.ToString());
                sl.TotalPrice = decimal.Parse(grdItems.Rows[i].Cells["Value"].Value.ToString());
                sl.UnitPrice = decimal.Parse(grdItems.Rows[i].Cells["Price"].Value.ToString());
                sl.ProductId = getProductId(grdItems.Rows[i].Cells["BarCode"].Value.ToString());
                newSale.SalesDetails.Add(sl);
            }
            newSale.DateAdded = DateTime.Now;
            newSale.Total = decimal.Parse(txtTotal.Text);
            newSale.Discount = decimal.Parse(txtDiscount.Text);
            newSale.FinalTotal = decimal.Parse(txtFinalTotal.Text);
           _ctx.Sales.Add(newSale);
           _ctx.SaveChanges();
            items = null;
            MessageBox.Show("Saved");
        }
    }

仅在实体框架和窗口窗体中保存第一行

您一遍又一遍地使用相同的SalesDetail对象。

您需要为循环中的每一行创建一个新行,如下所示:

//...
Sale newSale = new Sale();
for (int i = 0; i < grdItems.Rows.Count; i++)
{
    SalesDetail sl = new SalesDetail();
    //...
}
//...