簡體   English   中英

使用LINQ2SQL(Winforms)編輯DataGridView后提交更改

[英]Commit Changes after DataGridView edit using LINQ2SQL (Winforms)

給定一個像這樣設置BindingSource的DataGridView:

在winform上,我們使用名為myBindingScource的設計器添加一個BindingSource對象。 然后在Form.Designer.cs上我們將它添加到InitializeComponents()

myBindingSource.DataSource = typeof(MyLinq.Person); //Mylinq is the autogenerated Linq Model/Diagram

之后,我們在表單中執行以下操作:

myDataView.DataSource = myBindingSource;

然后我們有一個填充網格的方法......

using ( myDataContext mdc = new MyDataContext() )
{
    myDataView.DataSource = from per in mdc.person
                            select per;
}

另外,我已經在設計時設置了列,一切都顯示正常。 由於LINQ 2 SQL沒有返回Anonymous,因此“myDataView”是可編輯的,這就是問題......

問題是: 我如何堅持這些變化?

數據網格中有很多事件,我不確定哪一個更合適。 即使我嘗試了其中一個事件,我仍然不知道我需要執行什么代碼才能將這些更改發送回數據庫以保持更改。

我記得在ADO.NET DataSet時代,你會做dataadapter.Update(dataset);

還想象一下,retrieve和persist()都在Business Layer上,方法簽名如下所示:

public void LoadMyDataGrid(DataGridView grid);

該方法采用表單的網格,並使用上面顯示的LINQ2SQL查詢填充它。

現在我想創建一個這樣的方法:

public void SaveMyDataGrid(DataGridView grid); // or similar

這個想法是這個方法不在同一個類(形式)上,許多例子都傾向於假設一切都在一起。

RowValidated事件將是一個檢查是否有時間保持對數據庫的更改的好地方。

    this.dataGridView1.RowValidated += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowValidated);

    private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        MyLinq.Person person = dataGridView1.Rows[e.RowIndex].DataBoundItem as MyLinq.Person;

        if (person != null)
        {
            // save this person back to data access layer
        }
    }

編輯后:

我不會將數據網格實例傳回服務層。 我將傳回IEnumerable<MyLinq.Person>IList<MyLinq.Person>然后迭代服務層中的集合,並根據執行的邏輯; 將更改保留到數據訪問層(您的數據庫)

DataContext對象上的“save”方法是SubmitChanges()

using (MyContext c = new MyContext())
{
     var q = (from p in c.People
             where p.Id == 1
             select p).First();
     q.FirstName = "Mark";
     c.SubmitChanges();
}

正如Michael G所提到的,您需要收集更改,並將它們傳遞回bll對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM