VB 9 linq to sql实做1

前两天刚刚下载了Orcas beta 1,今天来玩一下传说中的linq,看看怎么通过linq语法来操作数据库。

首先创建一个Console Application,然后创建一个名称为DBForums.mdf的Service-based Database。然后在

DBForums.mdf中添加一个名称为UserInfo的表,表结构如下:

字段名称 字段属性 字段说明
UserID int PK,自增加字段
UserName Varchar(50)
CreateTime DateTime
LastLoginTime DataTime
Password Varchar(50)
Address Varchar(100)

添加完成后在工程中添加一个Linq to SQL项,项名称设置为DBForums.dbml,然后在Server Explorer中将

DBForums.mdf中的UserInfo拖放到DBForums.dbml的设计界面上。在程序中就可以访问DBForums数据库了

Private db As New DBForumsDataContext

Dim users() = {_
New UserInfo With {.UserName = " chenrui " ,_
.Password
= " 12345 " ,_
.Address
= " HU " ,_
.CreateTime
= Now},_
New UserInfo With {.UserName = " Li " ,_
.Password
= " 223344 " ,_
.Address
= " Bei " ,_
.CreateTime
= Now},_
New UserInfo With {.UserName = " Zhang " ,_
.Password
= " 223344 " ,_
.Address
= " Bei " ,_
.CreateTime
= Now}_
}

' Select
Dim UserFromBei = FromUserInfo In usersWhereUserInfo.Address = " Bei "
For Each u In UserFromBei
Console.WriteLine(u.UserName)
Next

' Insert
For Each u In users
db.UserInfos.Add(u)
Next
db.SubmitChanges()

' selectfromdb
Dim q = Fromc In db.UserInfos Select c.UserName
For Each uName In q
Console.WriteLine(
" Selected: " + uName)
Next

Console.ReadLine()

因为在DBForums.dbml中定义了UserInfo,因此在代码中可以访问。首先定义了一个UserInfo数组,然后

可以通过Linq查询,通过DBForums.dbml的DBForumsDataContext对象执行插入和数据库查询操作。

你可能感兴趣的:(数据结构,sql,sql,server,vb,LINQ)