Linq to SQL - SubmitChanges不起作用

时间:2011-11-15 23:51:17

标签: linq-to-sql

所以 - 我有一个带有一个员工表的MySQL数据库,使用Devart Linq to SQL(用于MySQL) 它在DataContext中有一个主键, 我可以加载gridview, 选择一行, 将Staff =的实例设置为在gridview中选择的ID和Name或行 将Textbox =设置为Staff名称 更改文本框并将对象Staff.Name设置为文本框.....

但是我无法将更改提交回db !!!!可能是我作为新手做的蠢事。

Public Class Form1

    Dim db As New MydbContext.MydbDataContext
    Dim bs = New BindingSource
    Dim Staff As New MydbContext.Employee

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' load employee data from MySQL db in datagrid

        Dim StaffQuery = From s In db.Employees Select s
        bs.DataSource = StaffQuery
        DataGridView1.DataSource = bs

        ' this works fine

    End Sub

    Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick

        'create an instance of the object Staff with the ID and Name from the datagrid
        'is there a better way to do this?

        Staff.EmployeeID = DataGridView1.Rows(e.RowIndex).Cells("EmployeeID").Value
        Staff.Name = DataGridView1.Rows(e.RowIndex).Cells("Name").Value
        MsgBox(Staff.EmployeeID & " " & Staff.Name)
        TextBox1.Text = Staff.Name

        'this works fine

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Staff.Name = TextBox1.Text   'edit the Name
        MsgBox(Staff.EmployeeID & " " & Staff.Name)  ' this works - shows new Staff.Name from textbox
        db.SubmitChanges()   ' this fails to make db changes

    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

我相信您需要添加db.Staffs.InsertOnSubmit(Staff)

其中StaffsStaff个对象集合的名称。

但是,为什么不在用户按下保存按钮时创建新的Staff对象,而不是始终保持上下文和对象?

最后,您可以在数据库上下文中调用GetChangeSet()以查看待处理的更改。这可以帮助您了解何时发生奇怪的事情。