Winform BindingNavigator不将项目保存到数据库

本文关键字:保存 数据库 项目 BindingNavigator Winform | 更新日期: 2023-09-27 17:52:33

我设计了一个使用ADO绑定到我的数据库的WinForm。Net实体框架。加载时,我的详细信息表单将填充来自数据库的数据。

我可以浏览项目,但是我不能添加、保存或更新项目。

下面是我的表单代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
    cpdEntities dbcontext;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        dbcontext = new cpdEntities();
        cpd_recipientsBindingSource.DataSource = dbcontext.cpd_recipients.ToList();
    }

    private void cpd_recipientsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        dbcontext = new cpdEntities();
        dbcontext.SaveChanges();
    }
}

}

Winform BindingNavigator不将项目保存到数据库

下面是一个使用EntityFramework 4的简单示例

如何加载:

 using (var con = new cpdEntities())
 {
    cpd_recipientsBindingSource.DataSource = con.cpd_recipients.ToList();
 }

如何插入和更新:

   if (cpd_recipientsBindingSource.Current == null) return;
        using (var con = new cpdEntities())
        {
            var p = new Customer()
            {
                CustomerId = ((cpd_recipients)cpd_recipientsBindingSource.Current).Id,
                CustomerIdNo = IdNoTextBox.Text,
                CustomerName = CustomerNameTextBox.Text
            };
            var cus = new Customer();
            if (p.CustomerId > 0)
                cus = con.Customers.First(c => c.CustomerId == p.CustomerId);
            cus.CustomerId = p.CustomerId;
            cus.CustomerIdNo = p.CustomerIdNo;
            cus.CustomerName = p.CustomerName;
            if (p.CustomerId == 0)
                con.Customers.AddObject(cus);
            con.SaveChanges();
            int i = cus.CustomerId;//SCOPE_IDENTITY
        }
    }

看起来像是在每个事件中重新实例化DbContext类。从saveItem事件中删除重新实例化DbContext,然后再试一次。