在向大家详细介绍Linq UserInfo之前,首先让大家了解下linq语法,然后全面介绍Linq UserInfo。
前两天刚刚下载了Orcas beta 1,今天来玩一下传说中的linq,看看怎么通过linq语法来操作数据库。首先创建一个Console Application,然后创建一个名称为DBForums.mdf的Service-based Database。然后在DBForums.mdf中添加一个名称为Linq UserInfo的表。
添加完成后在工程中添加一个Linq to SQL项,项名称设置为DBForums.dbml,然后在Server Explorer中将DBForums.mdf中的Linq 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 = From UserInfo In users Where UserInfo.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()
- 'select from db
- Dim q = From c In db.UserInfos Select c.UserName
- For Each uName In q
- Console.WriteLine("Selected : " + uName)
- Next
- Console.ReadLine()
因为在DBForums.dbml中定义了Linq UserInfo,因此在代码中可以访问。首先定义了一个Linq UserInfo数组,然后可以通过Linq查询,通过DBForums.dbml的DBForumsDataContext对象执行插入和数据库查询操作。
【编辑推荐】