我正在关注本教程http://www.codeproject.com/Articles/739164/Entity-Framework-Tutorial-for-Beginners
它似乎适合我们的VB.NET 4.0 WinForms应用程序。但我对更新部分感到困惑。
基本上我可以很好地创建和阅读部分,但不能更新。
这是我的插入/创建代码。
Private Sub btnInsert_Click(sender As System.Object, e As System.EventArgs) Handles btnInsert.Click
Dim db = New MyEntities
Dim objEmp As Employee
objEmp = PopulateEmployeeFromTextboxes() ' this does things like objEmp.Firstname = txtFirstName.text
db.Employees.AddObject(objEmp)
db.SaveChanges()
MessageBox.Show("Insert/Update success!")
End Sub
读取代码就是这样 - 点击一下按钮,就会有一个下拉列表来选择员工。一旦选择了员工,就会从数据库中的数据更新文本框(即txtFirstName)。到目前为止一直很好,但我不确定如何获取现有记录并更新它。
Private Sub btnSelect_Click(sender As System.Object, e As System.EventArgs) Handles btnSelect.Click
Dim db = New MyEntities
Dim empQuery = From emp In db.Employees Select emp
Dim empList As List(Of Employee) = empQuery.ToList
cbEmployee.DataSource = empList
cbEmployee.DisplayMember = "FirstName"
End Sub
答案 0 :(得分:0)
在挖掘源代码时找到答案,就在这里。基本上在更新时使用数据库中的LINQ检索对象,更新对象中的值,然后提交更改。
If (Not String.IsNullOrEmpty(selEmployee.EmpId)) Then ' UPDATE
Dim empId As Int32 = Convert.ToInt32(selEmployee.EmpId)
Dim empQuery = From emp In db.Employees
Where emp.EmpId = empId
Select emp
objEmp = empQuery.Single()
objEmp.HREmpId = txtHREmpId.Text
objEmp.FirstName = txtFirstName.Text
objEmp.LastName = txtLastName.Text
objEmp.Address = txtAddress.Text
objEmp.City = txtCity.Text
Else
objEmp = PopulateEmployeeFromTextboxes() ' this does things like objEmp.Firstname = txtFirstName.text
db.Employees.AddObject(objEmp)
End If
db.SaveChanges()
RefreshData()
selEmployee = Nothing