【问题标题】:Commit Changes after DataGridView edit using LINQ2SQL (Winforms)使用 LINQ2SQL (Winforms) 在 DataGridView 编辑后提交更改
【发布时间】:2009-10-26 16:07:59
【问题描述】:

给定一个 DataGridView,它的 BindingSource 设置如下:

在 winform 上,我们使用设计器添加一个 BindingSource 对象,称为 myBindingScource。 然后在 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 没有返回匿名,“myDataView”是可编辑的,问题来了……

问题是:我如何保持这些更改?

数据网格中有几十个事件,我不确定哪一个更合适。即使我尝试其中一个事件,我仍然不知道我需要执行什么代码才能将这些更改发送回数据库以保持更改。

我记得在 ADO.NET DataSet 时代,你会做 dataadapter.Update(dataset);

还可以想象,retrieve 和 persist() 都在业务层上,方法签名如下所示:

public void LoadMyDataGrid(DataGridView grid);

该方法获取表单的网格并使用上面显示的 LINQ2SQL 查询填充它。

现在我想创建一个这样的方法:

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

这个想法是这个方法不在同一个类(表单)上,很多例子倾向于假设一切都在一起。

【问题讨论】:

    标签: c# linq-to-sql commit dataview


    【解决方案1】:

    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> 然后遍历您的服务层中的集合,具体取决于执行的逻辑;将更改持久化到数据访问层(您的数据库)

    【讨论】:

    • 我对代码的“//保存此人”部分感兴趣。我有一个来自数据库的人员对象,并被放置在一行中。该行已编辑。现在我希望 LINQ 将这些更改放回去。在 NHIBERNATE 等中,每个类/对象都有“.save()”或“.persist()”方法。但我不知道如何告诉 LINQ(通过阅读下面的 cloggings 示例)更新 person 对象。
    • 我在这里找到了解决方案(附加):geekswithblogs.net/michelotti/archive/2007/12/17/117791.aspx
    【解决方案2】:

    DataContext 对象的“保存”方法是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 对象。

    【讨论】:

    • 但是如果我有一个来自 Datagrid 中行的 People 对象,我如何告诉 DataContext 更新那个“Person”?我记得在其他 OR 映射器中,每个对象都有一个 .persist() 或 .save() 方法。从 MichaelG 的代码中检索到的对象是“Person”对象。我需要告诉 LINQ,继续更新这个人。
    • 看上面的评论,解决办法是我需要把断开的对象“附加”回来,我需要时间戳。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多