dev221 vb中的linq:未来之路download.microsoft.com/download/3/7/3/3738f4f6-56... · linq项目...
TRANSCRIPT
Dev221 Dev221 VBVB中的中的LINQ:LINQ:未来之路未来之路
课程内容概述课程内容概述
LINQLINQ的字面含义是的字面含义是““语言集成的查询语言集成的查询””-- Language Language INtegratedINtegrated QueryQuery。它是下一版。它是下一版Visual StudioVisual Studio的功的功能重点之一。它扩展了能重点之一。它扩展了VBVB,让大家可以使用类似,让大家可以使用类似SQLSQL的语言来操作多个数据源,例如的语言来操作多个数据源,例如Object Object Collection, XML, DatasetCollection, XML, Dataset以及以及DatabaseDatabase。。
课程内容安排课程内容安排
LINQLINQ项目概述项目概述
基于对象数据的基于对象数据的LINQLINQ基于基于SQLSQL的的LINQ(DLinqLINQ(DLinq) ) 基于基于XMLXML的的LINQ(XLinqLINQ(XLinq) )
Visual Basic 9.0Visual Basic 9.0
简化查询数据简化查询数据在在VBVB语言中集成查询操作语言中集成查询操作
对对象数据、关系型数据和对对象数据、关系型数据和XMLXML数据建立统一的查询数据建立统一的查询
便于使用便于使用XMLXML快速生成快速生成XMLXML文档文档
简化性、一致性简化性、一致性&&提高生产效率提高生产效率
Language Integrated QueryLanguage Integrated Query
LINQLINQ项目项目
StandardStandardQueryQuery
OperatorsOperators
ObjectsObjects
DLinqDLinq(ADO.NET)(ADO.NET)
XLinqXLinq((System.XMLSystem.XML))
<book><title/><author/><year/><price/>
</book>
XMLXML
.NET Language Integrated Query.NET Language Integrated Query
VBVB C#C# OthersOthers……
SQLSQL
LINQLINQ的创新点的创新点
对对象数据、关系型数据和对对象数据、关系型数据和XMLXML数据建立统一的数据建立统一的查询和转换查询和转换
VBVB查询语法类似于查询语法类似于SQLSQL和和XqueryXquery
查询的类型检查、查询的类型检查、intellisenseintellisense和代码重构和代码重构
语言语言/API/API设计具有可扩展性设计具有可扩展性
语言的创新点语言的创新点
Implicitly typed localsImplicitly typed locals
隐式类型的局部变量隐式类型的局部变量
Extension methodsExtension methodsExtensionExtension方法方法
Inline functionsInline functions内联函数内联函数
Object Object initializersinitializers对象初始值对象初始值
Anonymous typesAnonymous types匿名类型匿名类型
Query expressionsQuery expressions查询表达式查询表达式
Dim x = 5Dim x = 5
<Extension><Extension>Sub Sub Randomize(colRandomize(col As Collection)As Collection)
Function(cFunction(c) ) c.Namec.Name
New Point { x := 1, y := 2 }New Point { x := 1, y := 2 }
New { New { c.Namec.Name, , c.Phonec.Phone }}
From From …… Where Where …… SelectSelect
查询语法查询语法
ProjectProject SelectSelect <<exprexpr>>
FilterFilter WhereWhere <<exprexpr>>
TestTest Any(Any(<<exprexpr>>)), , All(All(<<exprexpr>>))
JoinJoin <<exprexpr> > JoinJoin <<exprexpr> > OnOn <<exprexpr>>
GroupGroup GroupGroup ByBy <<exprexpr>>
AggregateAggregate Count(Count(<<exprexpr>>)), , Sum(Sum(<<exprexpr>>)), , Min(Min(<<exprexpr>>)), , Max(Max(<<exprexpr>>)), , AvgAvg((<<exprexpr>>))
PartitionPartition TopTop <<exprexpr>>
SetSet DistinctDistinct, , UnionUnion, , IntersectIntersect, , ExceptExcept
OrderOrder OrderOrder ByBy <<exprexpr>>
ConvertConvert ToArrayToArray,, ToListToList, , ToBindingListToBindingList
CastCast As As <<typenametypename>, >, OfType(OfOfType(Of T)T)
关系型数据的关系型数据的DLinqDLinq
SqlConnectionSqlConnection c = new c = new SqlConnectionSqlConnection((……););c.Openc.Open();();SqlCommandSqlCommand cmdcmd = new = new SqlCommandSqlCommand((@"SELECT @"SELECT c.Namec.Name, , c.Phonec.Phone
FROM Customers cFROM Customers cWHERE WHERE c.Cityc.City = @p0");= @p0");
cmd.Parameters["@p0"] = "London";cmd.Parameters["@p0"] = "London";DataReaderDataReader drdr = = c.Execute(cmdc.Execute(cmd););while (while (dr.Readdr.Read()) {()) {
string name = r.GetString(0);string name = r.GetString(0);string phone = r.GetString(1);string phone = r.GetString(1);DateTimeDateTime date = r.GetDateTime(2);date = r.GetDateTime(2);
}}r.Closer.Close();();
当前访问数据的方法当前访问数据的方法
Queries in Queries in quotesquotes
Loosely bound Loosely bound argumentsarguments
Loosely typed Loosely typed result setsresult sets
No compile No compile time checkstime checks
Public Class Customer Public Class Customer ……
Public Class NorthwindPublic Class NorthwindInherits DataContextInherits DataContext
Public Property Customers As Table(Of Customer)Public Property Customers As Table(Of Customer)……
End ClassEnd Class
Dim db As New Northwind(Dim db As New Northwind(……))Dim contacts = _ Dim contacts = _
From c in db.Customers _From c in db.Customers _Where c.City = "London"Where c.City = "London"Select c.Name, c.Phone Select c.Name, c.Phone
关系型数据的关系型数据的DLinq DLinq
使用使用DLingDLing访问数据访问数据
Classes Classes describe datadescribe data
Strongly typed Strongly typed connectionconnection
Integrated Integrated query syntaxquery syntax
Strongly typed Strongly typed resultsresults
Tables are like Tables are like collectionscollections
编写DLinq应用程序编写DLinq应用程序
关系型数据的关系型数据的DLinq DLinq
使用语言中的数据访问使用语言中的数据访问影射影射tables/rows tables/rows 到类到类//对象对象
基于基于ADO.NET ADO.NET 以及以及.NET Transactions.NET Transactions
影射影射
工具生成或手工编写工具生成或手工编写
其它其它
可以使用存储过程可以使用存储过程
支持其实数据库支持其实数据库 ((需插件需插件))
XMLXML数据的数据的XLinq XLinq
Dim doc As New XmlDocument()Dim doc As New XmlDocument()Dim contacts As XMLElement = doc.CreateElement("contacts")Dim contacts As XMLElement = doc.CreateElement("contacts")For Each Dim c in CustomersFor Each Dim c in Customers
If (c.Country = "USA") If (c.Country = "USA") Dim e As XMLElement = doc.CreateElement("contact")Dim e As XMLElement = doc.CreateElement("contact")Dim name As XMLElement = doc.CreateElement("name")Dim name As XMLElement = doc.CreateElement("name")name.InnerText = c.CompanyNamename.InnerText = c.CompanyNamee.AppendChild(name)e.AppendChild(name)Dim phone As XMLElement = doc.CreateElement("phone")Dim phone As XMLElement = doc.CreateElement("phone")phone.InnerText = c.Phonephone.InnerText = c.Phonee.AppendChild(phone)e.AppendChild(phone)contacts.AppendChild(e)contacts.AppendChild(e)
End IfEnd IfNextNextdoc.AppendChild(contacts)doc.AppendChild(contacts)
当前当前XMLXML编程方式编程方式
<contacts><contacts><contact><contact>
<name>Great Lakes Food</name><name>Great Lakes Food</name><phone>(503) 555<phone>(503) 555--7123</phone>7123</phone>
</contact></contact>……
</contacts></contacts>
Imperative Imperative modelmodel
Document Document centriccentric
No integrated No integrated queriesqueries
Memory Memory intensiveintensive
XMLXML数据的数据的XLinqXLinq
DimDim contacts contacts AsAs NeNew XElement("contacts",w XElement("contacts", __FFrom c in customersrom c in customers _ _ WWhere c.Country = "USAhere c.Country = "USA““ __SSelect elect NNew XElement("contact",ew XElement("contact", __
new XElement("name", c.CompanyName),new XElement("name", c.CompanyName), __new XElement("phone", c.Phone)new XElement("phone", c.Phone) __
))))
使用使用XLinqXLinq进行编程进行编程Declarative Declarative
modelmodel
ElementElementcentriccentric
Integrated Integrated queriesqueries
Smaller and Smaller and fasterfaster
在在Visual BasicVisual Basic中集成中集成XMLXML
Dim contacts = _Dim contacts = _<contacts><contacts><%=<%= __
From c In customers _From c In customers _Where c.Country = "USA" _Where c.Country = "USA" _Select <contact>Select <contact>
<name><name><%=<%= c.CompanyName c.CompanyName %>%></name></name><phone><phone><%=<%= c.Phone c.Phone %>%></phone></phone>
</contact> _</contact> _%>%>
</contacts></contacts>
利用利用XLinqXLinq在在VBVB中进行中进行XMLXML编程编程Infers XLinq Infers XLinq XElementXElement
No conceptual No conceptual barrierbarrier
Expression holes for Expression holes for computed values computed values
使用XLinq使用XLinq
XMLXML数据的数据的XLinqXLinq
与语言集成的与语言集成的XMLXML查询查询具有具有XPath / XQueryXPath / XQuery的表达能力的表达能力
将将VBVB或或C#C#作为编程语言作为编程语言XMLXML和代码之间无任何概念上的障碍和代码之间无任何概念上的障碍
利用利用DOMDOM的经验的经验元素为中心元素为中心,,而不是文档为中心而不是文档为中心
对称的元素对称的元素//属性属性APIAPI功能性的构造功能性的构造文本结点仅仅是字符串文本结点仅仅是字符串简化的简化的XMLXML命名空间支持命名空间支持更快且更小更快且更小
LINQLINQ项目项目
.NET.NET的的Language Integrated Query Language Integrated Query 在在VB9.0VB9.0和和C#3.0C#3.0的语言中具有内建的查询语法的语言中具有内建的查询语法
标准查询操作标准查询操作对任意对任意.NET.NET集合的类似集合的类似SQLSQL的查询的查询
DLinqDLinq可查询的数据访问框架可查询的数据访问框架
XLinqXLinq可查询的可查询的XML DOM, XML DOM, 并且更小并且更小, , 更快更快
总结总结
Language Integrated QueryLanguage Integrated Query LanguageLanguage 的优点的优点对于对象数据对于对象数据,,关系型数据和关系型数据和XMLXML数据的统一查询数据的统一查询查询的类型查询的类型在在VBVB和和C#C#中的类似中的类似SQLSQL和和XQueryXQuery的查询的查询仅支持仅支持.NET.NET平台平台
更多信息更多信息主页主页: : http://msdn.microsoft.com/netframework/future/linq/http://msdn.microsoft.com/netframework/future/linq/可下载可下载Customer Tech PreviewsCustomer Tech Previews版本版本!!
Contact: [email protected]: [email protected]
我们需要您的反馈意见我们需要您的反馈意见
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
XML Member BindingXML Member BindingXMLXML成员绑定成员绑定
Late binding covers all XML axesLate binding covers all XML axes延后绑定所有的延后绑定所有的XML axesXML axes
Dim cosmos As XElement = GetCurrentLinkCosmos().RootDim cosmos As XElement = GetCurrentLinkCosmos().RootDim ver As Double = CDbl(cosmos.Attribute("version"))Dim ver As Double = CDbl(cosmos.Attribute("version"))Dim item As XElement = First(cosmos.Descendents("item"))Dim item As XElement = First(cosmos.Descendents("item"))Dim created As Date = CDate(item.Element("linkcreatedDim created As Date = CDate(item.Element("linkcreated““))))
Dim cosmos As XElement = GetCurrentLinkCosmos().RootDim cosmos As XElement = GetCurrentLinkCosmos().RootDim ver As Double = CDbl(cosmos.@version)Dim ver As Double = CDbl(cosmos.@version)Dim item As XElement = cosmosDim item As XElement = cosmos……<item>.Value<item>.ValueDim created As Date = CDate(item.<linkcreated>)Dim created As Date = CDate(item.<linkcreated>)
AttributesAttributes
DescendentsDescendentsElementsElements
XML LiteralsXML LiteralsXML LiteralsXML Literals
Shorthand for object creationShorthand for object creation编写对象生成代码编写对象生成代码Dim emp = _Dim emp = _
<employee><employee><name>Joe</name><name>Joe</name><age>28</age><age>28</age><department id="432"><department id="432">
<deptname>Engineering</deptname><deptname>Engineering</deptname></department></department>
</employee></employee>
Dim emp = _Dim emp = _New XElement("employee", _New XElement("employee", _
New XElement("name", "Joe"), _New XElement("name", "Joe"), _New XElement("age", 28), _New XElement("age", 28), _New XElement("department", _New XElement("department", _
New XElement("name", "Engineering"), _New XElement("name", "Engineering"), _New XAttribute("id", 432)))New XAttribute("id", 432)))
Deferred Query ExecutionDeferred Query Execution向后优先解析的查询表达式向后优先解析的查询表达式Dim custs() As Customer = SampleData.GetCustomers()Dim custs() As Customer = SampleData.GetCustomers()
custscusts
PhonePhoneNameNameIDID
Dim q = Select c.City From c In custs Where c.State = "WA"Dim q = Select c.City From c In custs Where c.State = "WA"
Dim q = custs.Where(AddressOf _Filter1).Select(AddressOf _ProjecDim q = custs.Where(AddressOf _Filter1).Select(AddressOf _Project1)t1)
SelectSelect
AddressOf AddressOf _Project1_Project1
Dim names() As String = q.ToArray()Dim names() As String = q.ToArray()
namesnames
AddressOf _Filter1AddressOf _Filter1
WhereWhere
Expression TreesExpression Trees 表达式树表达式树
Defer code interpretationDefer code interpretation向后优先解析的代码向后优先解析的代码
Dim f As Predicate(Of Customer)Dim f As Predicate(Of Customer) = (c) c.State = "CA"= (c) c.State = "CA"
Dim e As Expression(Of Predicate(Of Customer))Dim e As Expression(Of Predicate(Of Customer)) = (c) c.State = "CA"= (c) c.State = "CA"
Dim e As Expression(Of Predicate(Of Customer))Dim e As Expression(Of Predicate(Of Customer)) = _= _New Expression(Of Predicate(Of Customer))(New Expression(Of Predicate(Of Customer))(
New BinaryExpression(ExpressionType.EQ,New BinaryExpression(ExpressionType.EQ,New PropertyExpression(New PropertyExpression(
New ParameterExpression(0),New ParameterExpression(0),GetType(Customer).GetProperty("State")GetType(Customer).GetProperty("State")
),),New ConstantExpression("CA")New ConstantExpression("CA")
))))
System.Query.Expression(Of T)System.Query.Expression(Of T)where T is a delegate typewhere T is a delegate type
Extension IntArrExtensions To Integer()Extension IntArrExtensions To Integer()Function Sort() As Integer()Function Sort() As Integer()
……End FunctionEnd Function
ReadOnly Property Sum() As IntegerReadOnly Property Sum() As IntegerGetGet
……End GetEnd Get
End PropertyEnd PropertyEnd ExtensionEnd Extension
Extension MethodsExtension Methods扩展模型扩展模型
Extend existing types with new methodsExtend existing types with new methods使用新方法扩展存在的类型使用新方法扩展存在的类型
Imports IntegerArrExtensionsImports IntegerArrExtensions
Dim values() As Integer = GetValues()Dim values() As Integer = GetValues()Console.WriteLine(IntegerArrExtensions.Sum(IntegerExtensions.SorConsole.WriteLine(IntegerArrExtensions.Sum(IntegerExtensions.Sort(values))t(values))
Dim values() As Integer = GetValues()Dim values() As Integer = GetValues()Console.WriteLine(values.Sort().Sum())Console.WriteLine(values.Sort().Sum())
obj.Foo(x, y)obj.Foo(x, y)
XXX.Foo(obj, x, y)XXX.Foo(obj, x, y)
Simple Type InferenceSimple Type Inference简单类型引用简单类型引用
Variable type inferred from initializerVariable type inferred from initializer由初始值推断的变量类型由初始值推断的变量类型
Dim x = 5Dim x = 5Dim s = "Hello"Dim s = "Hello"Dim d = 1.0Dim d = 1.0Dim numbers = New Integer() {1, 2, 3}Dim numbers = New Integer() {1, 2, 3}Dim orders = new Dictionary(Of Integer, Order)()Dim orders = new Dictionary(Of Integer, Order)()
All types are All types are Object!Object!
IntegerIntegerStringString
DoubleDouble
Add link to external Community websiteAdd link to external Community websiteList top 3 newsgroups related to this slideList top 3 newsgroups related to this slide
112233
Advise when your next chat isAdvise when your next chat isNext user group meeting you will be atNext user group meeting you will be atAdd Other related 3rd party sitesAdd Other related 3rd party sites
填反馈表填反馈表
讲师的讲师的Chalk TalkChalk Talk和其他和其他SessionSession
与本次主题有关的与本次主题有关的SessionSession和活动和活动