本实例实现创建
LINQ To SQL
类对数据库进行插入、修改和删除的操作;以下是
具体步骤:
1
)建立
windows
窗体应用项目文件
2
)选择
'
项目
添加新项
'
菜单,在类别中选择
'
常用项
'
,在
'
模板
'
视图中选择
'LINQ to
sql '
类,系统自动添加用户命名的
LINQ to SQL
文件(
dataclasses1.dbml
)
3
)选择“视图
/
服务器资源管理”菜单,则会弹出【服务器资源管理器】窗口,在
此窗口中展开“数据连接
idcjomhgsysql.Northwind.dbo
表
Shippers
”节点,拖动节
点到
LINQ To SQL
对象关系设计器的设计视图左边的一个窗格,系统将自动添加
数据表
Shippers
;
4
)选择“生成
生成
MyForm
”菜单,当前项目会执行保存、编译和链接等操作。
5
)从【工具箱】窗口中拖动一个
DataGridView
控件(
DatagridView1
)和四个
Button
控件到应用程序窗体【
Form1.vb[
设计
]
】视图,然后为四个
Button
控件的
Click
事件添加以下代码:
‟
显示数据
Private sub Button1_Click(byval sender as system.object, byval e as system.eventargs)
handles Button1.click
Dim MyDC as new DataClasses1DataContext()
Dim MyQuery=From MyShipper In MyDC.Shippers Select MyShipper
Me.DataGridView1.DataSource=MyQuery
End Sub
„
插入数据
Private Sub Button2_Click(byval sender as system.object, byval e as system.eventargs)
handles Button2.click
Dim MyDC as new DataClasses1DataContext()
Dim MyShippers as new Shippers()
MyShippers.CompanyName=
”
GSY Group International
”
MyShippers.Phone=
”
00852-53962276
”
MyDC.Shippers.InsertOnSubmit(MyShippers)
MyDC.SubmitChanges()
Button1_Click(nothing,nothing)
End Sub
„
修改数据
Private Sub Button3_Click(byval sender as system.object, byval e as system.eventargs)
handles Button3.click
Dim MyDC as new DataClasses1DataContext()
Dim MyQuery=From MyShipper In MyDC.Shippers _
Where(MyShipper.CompanyName.Contains(
“
HongKong
”
)) _
Select MyShipper
For each Shipper in MyQuery
If(Shipper.CompanyName=
”
GSY Group International
”
) then
Shipper.Phone=
”
086-15219442276
”
End if
Next
MyDC.SubmitChanges()
Button1_Click(nothing,nothing)
End Sub
„
删除数据
Private Sub Button4_Click(byval sender as system.object, byval e as system.eventargs)
handles Button4.click
Dim MyDC as new DataClasses1DataContext()
Dim MyQuery=From MyShipper In MyDC.Shippers _
Where(MyShipper.CompanyName.Contains(
“
HongKong
”
)) _
Select MyShipper
While(MyQuery.Count()>0)
MyDC.Shippers.DeleteOnSubmit(MyQuery.First())
MyDC.SubmitChanges()
End While
MyDC.SubmitChanges()
Button1_Click(nothing,nothing)
End Sub