技术开发 频道

用LINQ to SQL进行数据层访问


    把下面的代码添加到你的WinForm类,以此启动一个DataContext会话,并填充窗体的文本框和DataGridViews:
Imports System.Data 
Imports System.Data.Linq
Imports System.Linq

Public Class frmLINQ2SQL
Private dcNwind As LINQ2SQLDataContext

Private Sub frmLINQ2SQL_Load(ByVal sender _
As System.Object, ByVal e _
As System.EventArgs) _
Handles MyBase.Load
dcNwind = New NwindDataContext
CustomerBindingSource.DataSource = _
dcNwind.Customer
End Sub
End Class
   
    LINQ2SQLDataContext假设你已经把LINQ to SQL设计器文件命名为LINQ2SQL.dbml。

    按F5构建并运行项目,然后检查OrdersDataGridView是否和Customer数据同步了,以及OrderDetailsDataGridView是否按照你选择的顺序显示了排列项。

探究设计器生成的类

    要学会并理解O/RM的处理过程,至少得研究LINQ2SQL.designer.vb文件或Northwind数据库的cs文件中自动生成的2000行实体类代码的一部分。为了简洁,很多例子中都使用了Shippers表的代码(Listing 2)。LIINQ to SQL的O/RM默认采用基于属性的映射;这段摘录的TableAttribute装饰把Shipper表映射到Shipper实体类:
<Global.System.Data.Linq.Table(Name:= _ 
"dbo.Shippers")> _
Partial Public Class Shipper
Implements Global.System.Data.Linq._
INotifyPropertyChanging, _
Global.System.ComponentModel._
INotifyPropertyChanged
...
End Class
   
    在设计器中,表名是作为Source属性值出现的。为了支持DataContext的数据跟踪特性,类实现了System.Data.Linq.INotifyPropertyChanging和System.ComponentModel.INotifyPropertyChanged接口。支持INotifyPropertyChanged接口就不必在object和databound控件之间加入BindingSource了。虽然如此,微软仍然建议添加BindingSource。

    O/R设计器在普通的列成员中加入了三个默认的ColumnAttribute名字/类型对:Storage(私有成员名字),Name(数据库的列名称),以及DBType(SQL Server数据类型):
<Global.System.Data.Linq.Column(Storage:= _ 
"_Phone", Name:="Phone", _
DBType:="NVarChar(24)")> _
Public Property Phone() As String
Get
Return Me._Phone
End Get
Set
If ((Me._Phone Is value) _
= false) Then
Me.OnPropertyChanging("Phone")
Me._Phone = value
Me.OnPropertyChanged("Phone")
End If
End Set
End Property
0
相关文章