2013-01-13 55 views
0

我設計了一個WinForm,它綁定到我的數據庫使用ADO.Net實體框架。在加載時,我的詳細信息表單將填充來自數據庫的數據。Winform BindingNavigator不保存項目到數據庫

我可以瀏覽項目,但是我無法添加,保存或更新項目。

下面是我的表單代碼:

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

}

+0

什麼EntityFramwework的版本? – spajce

+0

@spajce版本4 –

+0

看到我的答案。試着去了解。它很難編碼(格式)沒有Visual Studio的IDE :) – spajce

回答

0

這裏與EntityFramework 4

工作一個簡單的例子,如何加載:

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

如何INSERT和UPDATE:

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 
     } 
    } 
0

它看起來就像你重新實例你的DbContext類每個事件。從saveItem事件中刪除重新檢測DbContext並再次嘗試。

+0

我已經刪除了重新實例化,但仍然沒有保存。 –