创建新记录,从而在相关表中创建相同的新记录

时间:2016-02-08 06:15:53

标签: c# sql-server winforms entity-framework entity-framework-6

每次创建新PurchasedProduct并向其引用Product时,在插入表格后,该表格始终会创建一个新的Product并引用新的Purchase而不是引用现有的。

所以,我有这3个相关的表格: enter image description here

..这意味着PurchasedProduct可以包含多个Product,每个public partial class fmAddEditPurchase : Form { List<Product> products; Purchase purchase; public fmAddEditPurchase() { InitializeComponent(); Purchase = new Purchase(); Text = "Add New Purchase"; dtpDate.Value = DateTime.Now.Date; RefreshPurchasedProduct(); LoadProductList(); } private void RefreshPurchasedProduct() { List<PurchasedProduct> ppQuery = new List<PurchasedProduct>(); BindingSource bi = new BindingSource(); if (Purchase.PurchasedProducts.Count > 0) { using (var context = new dbKrunchworkContext()) { bi.DataSource = Purchase.PurchasedProducts. Join(products, x => x.Product, y => y, (x, y) => new { y.Product_Name, x.Price, x.Quantity }). ToList(); } } dgvPurchasedProduct.DataSource = bi; dgvPurchasedProduct.Refresh(); } private void LoadProductList() { using (var context = new dbKrunchworkContext()) { products = context.Products.ToList(); } cbProductName.DataSource = products. Select(x => x.Product_Name).ToList(); } private void btAddProduct_Click(object sender, EventArgs e) { decimal price = 0.0M; if (decimal.TryParse(tbPrice.Text, out price) && price > 0) { PurchasedProduct temp = Purchase.PurchasedProducts. FirstOrDefault( x => x.Product == products[cbProductName.SelectedIndex] && x.Price == price); if (temp == null) { PurchasedProduct newPP = new PurchasedProduct(); newPP.Product = products[cbProductName.SelectedIndex]; newPP.Purchase = Purchase; newPP.Quantity = (int)numQuantity.Value; newPP.Price = price; if (newPP.Product != null) { Purchase.PurchasedProducts.Add(newPP); } } else { temp.Quantity += (int)numQuantity.Value; } RefreshPurchasedProduct(); } } private void btSave_Click(object sender, EventArgs e) { try { Purchase.Received_Date = dtpDate.Value; Purchase.Total_Amount = decimal.Parse(tbTotalPrice.Text); Purchase.Note = tbNote.Text; using (var context = new dbKrunchworkContext()) { for (int i = 0; i < Purchase.PurchasedProducts.Count; i++) { PurchasedProduct pp = Purchase.PurchasedProducts.ElementAt(i); Product p = context.Products. FirstOrDefault(x => x.ID == pp.Product.ID); pp.Product = p; } } } catch (Exception) { } } } 代表购买的DialogResult() == DialogResult.OK以及购买的数量(数量)。

这是winform: enter image description here

以下是相关代码:

Form

这是从上面 private void Purchase_AddNewRecord() { fmAddEditPurchase addForm = new fmAddEditPurchase(); if (addForm.ShowDialog() == DialogResult.OK && addForm.Purchase.Total_Amount > 0) { using (var context = new dbKrunchworkContext()) { context.Purchases.Add(addForm.Purchase); context.SaveChanges(); } } } 收到Product后将新记录插入表格的主要表单。

{{1}}

示例:

enter image description here

我做了什么(+保存)

enter image description here

之后(请注意,它会创建一个新的{{1}}而不是使用旧版本)

enter image description here

1 个答案:

答案 0 :(得分:1)

您在表单的多种方法中使用DbContext的多个实例。

您遇到此问题,因为以下代码会将所有对象都放入Purshase图表中,并将所有对象标记为Added州。

private void Purchase_AddNewRecord()
{
    fmAddEditPurchase addForm = new fmAddEditPurchase();

    if (addForm.ShowDialog() == 
        DialogResult.OK && addForm.Purchase.Total_Amount > 0)
    {
        using (var context = new dbKrunchworkContext())
        {
            context.Purchases.Add(addForm.Purchase);
            context.SaveChanges();
        } 
    }
}

要解决此问题,您必须更改与Product实例相关的每个Purshase实例的状态,如下面的代码:

private void Purchase_AddNewRecord()
{
    fmAddEditPurchase addForm = new fmAddEditPurchase();

    if (addForm.ShowDialog() == 
        DialogResult.OK && addForm.Purchase.Total_Amount > 0)
    {
        using (var context = new dbKrunchworkContext())
        {
            context.Purchases.Add(addForm.Purchase);
            foreach (var purchasedProduct in addForm.Purchase.PurchasedProducts)
            {
                context.Entry(purchasedProduct.Product).State = EntityState.Unchanged;
            }
            context.SaveChanges();
        } 
    }
}

当您使用Windows窗体或WPF时,建议您不要像实际操作那样为每个方法创建DbContext的新实例。您必须通过为每个表单创建一个字段来创建一个表单。