0

我设计了一个使用 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();
    }
}

}

4

2 回答 2

0

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

于 2013-01-13T14:23:38.107 回答
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
        }
    }
于 2013-01-13T17:43:37.833 回答