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

时间:2013-01-13 13:45:00

标签: c# winforms entity-framework

我设计了一个使用ADO.Net Entity Framework绑定到我的数据库的WinForm。在加载时,我的详细信息表单中填充了数据库中的数据。

我可以浏览项目,但是我无法添加,保存或更新项目。

以下是我的表单的代码:

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();
    }
}

}

2 个答案:

答案 0 :(得分:0)

看起来您在每个事件中重新实例化DbContext类。从saveItem事件中删除重新实例化DbContext,并再次尝试。

答案 1 :(得分:0)

以下是使用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
        }
    }