forked from dotnet/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSource.vb
3305 lines (2830 loc) · 148 KB
/
Source.vb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'<snippetUsingSerialization>
'<snippetUsing>
Imports System.Linq
Imports System.Collections.Generic
Imports System.Text
Imports System.Data
Imports System.Data.Common
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
'</snippetUsing>
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
'</snippetUsingSerialization>
Imports System.Xml.Serialization
Imports System.Data.Common.CommandTrees
Imports System.Data.Metadata.Edm
Imports System.Data.EntityClient
'<snippetUsingEvents>
Imports System.ComponentModel
'</snippetUsingEvents>
Imports System.Data.SqlClient
Class Source1
'<snippetExecuteStoreCommandAndQueryForNewEntity>
Public Class DepartmentInfo
Private _startDate As DateTime
Private _name As String
Private _departmentID As Int32
Public Property DepartmentID() As Int32
Get
Return _departmentID
End Get
Set(ByVal value As Int32)
_departmentID = value
End Set
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property StartDate() As DateTime
Get
Return _startDate
End Get
Set(ByVal value As DateTime)
_startDate = value
End Set
End Property
End Class
Public Shared Sub ExecuteStoreCommands()
Using context As New SchoolEntities()
Dim DepartmentID As Integer = 21
' Insert the row in the Department table. Use the parameter substitution pattern.
Dim rowsAffected As Integer = context.ExecuteStoreCommand("insert Department values ({0}, {1}, {2}, {3}, {4})", _
DepartmentID, "Engineering", 350000.0R, "2009-09-01", 2)
Console.WriteLine("Number of affected rows: {0}", rowsAffected)
' Get the DepartmentTest object.
Dim department As DepartmentInfo = context.ExecuteStoreQuery(Of DepartmentInfo) _
("select * from Department where DepartmentID= {0}", _
DepartmentID).FirstOrDefault()
Console.WriteLine("ID: {0}, Name: {1} ", _
department.DepartmentID, department.Name)
rowsAffected = context.ExecuteStoreCommand("delete from Department where DepartmentID = {0}", _
DepartmentID)
Console.WriteLine("Number of affected rows: {0}", _
rowsAffected)
End Using
End Sub
'</snippetExecuteStoreCommandAndQueryForNewEntity>
Public Shared Sub CallCustomMethod()
Console.WriteLine("Starting method 'CallCustomMethod'")
'<snippetCallCustomMethod>
Dim orderId As Integer = 43662
Using context As New AdventureWorksEntities()
' Return an order and its items.
Dim order As SalesOrderHeader = context.SalesOrderHeaders.Include("SalesOrderDetails") _
.Where("it.SalesOrderID = @orderId", _
New ObjectParameter("orderId", orderId)).First()
Console.WriteLine("The original order total was: " & order.TotalDue)
' Update the order status.
order.Status = 1
' Increase the quantity of the first item, if one exists.
If order.SalesOrderDetails.Count > 0 Then
order.SalesOrderDetails.First().OrderQty += 1
End If
' Increase the shipping amount by 10%.
order.Freight = Decimal.Round(order.Freight * CDec(1.1), 4)
' Call the custom method to update the total.
order.UpdateOrderTotal()
Console.WriteLine("The calculated order total is: " & order.TotalDue)
' Save changes in the object context to the database.
Dim changes As Integer = context.SaveChanges()
' Refresh the order to get the computed total from the store.
context.Refresh(RefreshMode.StoreWins, order)
Console.WriteLine("The store generated order total is: " & order.TotalDue)
End Using
'</snippetCallCustomMethod>
End Sub
#Region "MrefMethods"
Public Shared Sub ContextClass()
Console.WriteLine("Starting method 'ContextClass'")
'<snippetObjectContext>
' Create the ObjectContext.
Dim context As New ObjectContext("name=AdventureWorksEntities")
' Set the DefaultContainerName for the ObjectContext.
' When DefaultContainerName is set, the Entity Framework only
' searches for the type in the specified container.
' Note that if a type is defined only once in the metadata workspace
' you do not have to set the DefaultContainerName.
context.DefaultContainerName = "AdventureWorksEntities"
Dim query As ObjectSet(Of Product) = context.CreateObjectSet(Of Product)()
' Iterate through the collection of Products.
For Each result As Product In query
Console.WriteLine("Product Name: {0}", result.Name)
Next
'</snippetObjectContext>
End Sub
Public Shared Sub ContextClass2()
Console.WriteLine("Starting method 'ContextClass'")
'<snippetObjectContext2>
' Create the ObjectContext.
Dim context As New ObjectContext("name=AdventureWorksEntities")
Dim query As ObjectSet(Of Product) = context.CreateObjectSet(Of Product)()
' Iterate through the collection of Products.
For Each result As Product In query
Console.WriteLine("Product Name: {0}", result.Name)
Next
'</snippetObjectContext2>
End Sub
Public Shared Sub ObjectQueryResult_GetEnumerator_Dispose()
Console.WriteLine("Starting method 'QueryResult'")
'<snippetQueryResult>
Using context As New AdventureWorksEntities()
Dim query As ObjectSet(Of Product) = context.Products
Dim queryResults As ObjectResult(Of Product) = Nothing
Dim enumerator As System.Collections.IEnumerator = Nothing
Try
queryResults = query.Execute(MergeOption.AppendOnly)
' Get the enumerator.
enumerator = DirectCast(queryResults, System.Collections.IEnumerable).GetEnumerator()
' Iterate through the query results.
While enumerator.MoveNext()
Dim product As Product = DirectCast(enumerator.Current, Product)
Console.WriteLine("{0}", product.Name)
End While
' Dispose the enumerator
DirectCast(enumerator, IDisposable).Dispose()
Finally
' Dispose the query results and the enumerator.
If queryResults IsNot Nothing Then
queryResults.Dispose()
End If
If enumerator IsNot Nothing Then
DirectCast(enumerator, IDisposable).Dispose()
End If
End Try
End Using
'</snippetQueryResult>
End Sub
Public Shared Sub ObjectStateEntry_CurrentValueGetModifiedPropertiesEntity()
Console.WriteLine("Starting method 'ObjectStateEntry_CurrentValueGetModifiedPropertiesEntity'")
'<snippetObjectStateEntry_GetModifiedProperties>
Dim orderId As Integer = 43680
Using context As New AdventureWorksEntities()
Dim order = (From o In context.SalesOrderHeaders
Where o.SalesOrderID = orderId
Select o).First()
' Get ObjectStateEntry from EntityKey.
Dim stateEntry As ObjectStateEntry = _
context.ObjectStateManager.GetObjectStateEntry(DirectCast(order, IEntityWithKey).EntityKey)
'Get the current value of SalesOrderHeader.PurchaseOrderNumber.
Dim rec1 As CurrentValueRecord = stateEntry.CurrentValues
Dim oldPurchaseOrderNumber As String = _
DirectCast(rec1.GetValue(rec1.GetOrdinal("PurchaseOrderNumber")), String)
'Change the value.
order.PurchaseOrderNumber = "12345"
Dim newPurchaseOrderNumber As String = _
DirectCast(rec1.GetValue(rec1.GetOrdinal("PurchaseOrderNumber")), String)
' Get the modified properties.
Dim modifiedFields As IEnumerable(Of String) = stateEntry.GetModifiedProperties()
For Each s As String In modifiedFields
Console.WriteLine("Modified field name: {0}", s)
Console.WriteLine("Old Value: {1}", oldPurchaseOrderNumber)
Console.WriteLine("New Value: {2}", newPurchaseOrderNumber)
Next
' Get the Entity that is associated with this ObjectStateEntry.
Dim associatedEnity As SalesOrderHeader = DirectCast(stateEntry.Entity, SalesOrderHeader)
Console.WriteLine("Associated Enity's ID: {0}", associatedEnity.SalesOrderID)
End Using
'</snippetObjectStateEntry_GetModifiedProperties>
End Sub
Public Shared Sub ObjectStateManager_TryGetObjectStateEntry()
Console.WriteLine("Starting method 'ObjectStateManager_TryGetObjectStateEntry'")
'<snippetObjectStateManager>
Dim orderId As Integer = 43680
Using context As New AdventureWorksEntities()
Dim objectStateManager As ObjectStateManager = context.ObjectStateManager
Dim stateEntry As ObjectStateEntry = Nothing
Dim order = (From o In context.SalesOrderHeaders
Where o.SalesOrderID = orderId
Select o).First()
' Attempts to retrieve ObjectStateEntry for the given EntityKey.
Dim isPresent As Boolean = objectStateManager.TryGetObjectStateEntry(DirectCast(order, IEntityWithKey).EntityKey, stateEntry)
If isPresent Then
Console.WriteLine("The entity was found")
End If
End Using
'</snippetObjectStateManager>
End Sub
Public Shared Sub ObjectQuery_GetResultType()
Console.WriteLine("Starting method 'ObjectQuery_GetResultType'")
'<snippetGetResultType>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product " & "FROM AdventureWorksEntities.Products AS product"
Dim query As New ObjectQuery(Of DbDataRecord)(queryString, context)
Dim type As TypeUsage = query.GetResultType()
If TypeOf type.EdmType Is RowType Then
Dim row As RowType = TryCast(type.EdmType, RowType)
For Each column As EdmProperty In row.Properties
Console.WriteLine("{0}", column.Name)
Next
End If
End Using
'</snippetGetResultType>
End Sub
Public Shared Sub ObjectQuery_Execute()
Console.WriteLine("Starting method 'ObjectQuery_Execute'")
'<snippetObjectQuery_Execute>
Using context As New AdventureWorksEntities()
Dim query As ObjectSet(Of Product) = context.Products
' Execute the query and get the ObjectResult.
Dim queryResult As ObjectResult(Of Product) = query.Execute(MergeOption.AppendOnly)
' Iterate through the collection of Product items.
For Each result As Product In queryResult
Console.WriteLine("{0}", result.Name)
Next
End Using
'</snippetObjectQuery_Execute>
End Sub
Public Shared Sub ObjectQuery_ToTraceStringEsql()
Console.WriteLine("Starting method 'ObjectQuery_ToTraceStringEsql'")
'<snippetObjectQuery_ToTraceStringEsql>
Dim productID = 900
Using context As New AdventureWorksEntities()
' Define the Entity SQL query string.
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product " & _
" WHERE product.ProductID = @productID"
' Define the object query with the query string.
Dim productQuery As New ObjectQuery(Of Product)(queryString, context, MergeOption.AppendOnly)
productQuery.Parameters.Add(New ObjectParameter("productID", productID))
' Write the store commands for the query.
Console.WriteLine(productQuery.ToTraceString())
End Using
'</snippetObjectQuery_ToTraceStringEsql>
End Sub
Public Shared Sub ObjectQuery_ToTraceStringLinq()
Console.WriteLine("Starting method 'ObjectQuery_ToTraceStringLinq'")
'<snippetObjectQuery_ToTraceStringLinq>
Dim productID = 900
Using context As New AdventureWorksEntities()
' Define an ObjectSet to use with the LINQ query.
Dim products As ObjectSet(Of Product) = context.Products
' Define a LINQ query that returns a selected product.
Dim result = From product In products _
Where product.ProductID = productID _
Select product
' Cast the inferred type var to an ObjectQuery
' and then write the store commands for the query.
Console.WriteLine(DirectCast(result, ObjectQuery(Of Product)).ToTraceString())
End Using
'</snippetObjectQuery_ToTraceStringLinq>
End Sub
Public Shared Sub ObjectQuery_ToTraceString()
Console.WriteLine("Starting method 'ObjectQuery_ToTraceString'")
'<snippetObjectQuery_ToTraceString>
Dim productID = 900
Using context As New AdventureWorksEntities()
' Define the object query for the specific product.
Dim productQuery As ObjectQuery(Of Product) = context.Products.Where("it.ProductID = @productID")
productQuery.Parameters.Add(New ObjectParameter("productID", productID))
' Write the store commands for the query.
Console.WriteLine(productQuery.ToTraceString())
End Using
'</snippetObjectQuery_ToTraceString>
End Sub
Public Shared Sub ObjectQuery_First()
Console.WriteLine("Starting method 'ObjectQuery_First'")
'<snippetObjectQuery_First>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
Dim productQuery1 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
' Get the first Product.
Dim productQuery2 As Product = productQuery1.First()
Console.WriteLine("Product Name: {0}", productQuery2.Name)
End Using
'</snippetObjectQuery_First>
End Sub
Public Shared Sub ObjectQuery_Where()
Console.WriteLine("Starting method 'ObjectQuery_Where'")
'<snippetObjectQuery_Where>
Dim productID = 900
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
Dim productQuery1 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As ObjectQuery(Of Product) = productQuery1.Where("it.ProductID = @productID")
productQuery2.Parameters.Add(New ObjectParameter("productID", productID))
' Iterate through the collection of Product items.
For Each result As Product In productQuery2
Console.WriteLine("Product Name: {0}; Product ID: {1}", result.Name, result.ProductID)
Next
End Using
'</snippetObjectQuery_Where>
End Sub
Public Shared Sub ObjectQuery_Top()
Console.WriteLine("Starting method 'ObjectQuery_Top'")
'<snippetObjectQuery_Top>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
Dim productQuery1 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As ObjectQuery(Of Product) = productQuery1.Top("2")
' Iterate through the collection of Product items.
For Each result As Product In productQuery2
Console.WriteLine("{0}", result.Name)
Next
End Using
'</snippetObjectQuery_Top>
End Sub
Public Shared Sub ObjectQuery_SelectValue()
Console.WriteLine("Starting method 'ObjectQuery_SelectValue'")
'<snippetObjectQuery_SelectValue>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
Dim productQuery1 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As ObjectQuery(Of Int32) = productQuery1.SelectValue(Of Int32)("it.ProductID")
For Each result As Int32 In productQuery2
Console.WriteLine("{0}", result)
Next
End Using
'</snippetObjectQuery_SelectValue>
End Sub
Public Shared Sub ObjectQuery_Select()
Console.WriteLine("Starting method 'ObjectQuery_Select'")
'<snippetObjectQuery_Select>
Dim productID = 900
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product" & _
" WHERE product.ProductID > @productID"
Dim productQuery1 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
productQuery1.Parameters.Add(New ObjectParameter("productID", productID))
Dim productQuery2 As ObjectQuery(Of DbDataRecord) = productQuery1.Select("it.ProductID")
For Each result As DbDataRecord In productQuery2
Console.WriteLine("{0}", result("ProductID"))
Next
End Using
'</snippetObjectQuery_Select>
End Sub
Public Shared Sub ObjectQuery_OrderBy()
Console.WriteLine("Starting method 'ObjectQuery_OrderBy'")
'<snippetObjectQuery_OrderBy>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
Dim productQuery1 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As ObjectQuery(Of Product) = productQuery1.OrderBy("it.ProductID")
' Iterate through the collection of Product items.
For Each result As Product In productQuery2
Console.WriteLine("{0}", result.ProductID)
Next
End Using
'</snippetObjectQuery_OrderBy>
End Sub
Public Shared Sub ObjectQuery_Intersect()
Console.WriteLine("Starting method 'ObjectQuery_Intersect'")
'<snippetObjectQuery_Intersect>
Dim productID1 = 900
Dim productID2 = 950
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products " & _
" AS product WHERE product.ProductID > @productID1"
Dim productQuery As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim queryString2 As String = "SELECT VALUE product FROM AdventureWorksEntities.Products " & _
" AS product WHERE product.ProductID > @productID2"
Dim productQuery2 As New ObjectQuery(Of Product)(queryString2, context, MergeOption.NoTracking)
Dim productQuery3 As ObjectQuery(Of Product) = productQuery.Intersect(productQuery2)
productQuery3.Parameters.Add(New ObjectParameter("productID1", productID1))
productQuery3.Parameters.Add(New ObjectParameter("productID2", productID2))
Console.WriteLine("Result of Intersect")
Console.WriteLine("------------------")
' Iterate through the collection of Product items
' after the Intersect method was called.
For Each result As Product In productQuery3
Console.WriteLine("Product Name: {0}", result.ProductID)
Next
End Using
'</snippetObjectQuery_Intersect>
End Sub
Public Shared Sub Projection_SkipLimit()
Console.WriteLine("Starting method 'Projection_SkipLimit'")
'<snippetProjection_SkipLimit>
Using context As New AdventureWorksEntities()
' Define the parameters used to define the "page" of returned data.
Dim skipValue As Integer = 3
Dim limitValue As Integer = 5
' Define a query that returns a "page" or the full
' Product data using the Skip and Top methods.
' When Top() follows Skip(), it acts like the LIMIT statement.
Dim query As ObjectQuery(Of Product) = _
context.Products.Skip("it.ListPrice", "@skip", _
New ObjectParameter("skip", skipValue)).Top("@limit", New ObjectParameter("limit", limitValue))
' Iterate through the page of Product items.
For Each result As Product In query
Console.WriteLine("ID: {0}; Name: {1}", result.ProductID, result.Name)
Next
End Using
'</snippetProjection_SkipLimit>
End Sub
Public Shared Sub Projection_GroupBy()
Console.WriteLine("Starting method 'Projection_GroupBy'")
'<snippetProjection_GroupBy>
Using context As New AdventureWorksEntities()
'<snippetComplexQueryBuilderMethod>
' Define the query with a GROUP BY clause that returns
' a set of nested LastName records grouped by first letter.
Dim query As ObjectQuery(Of DbDataRecord) = _
context.Contacts.GroupBy("SUBSTRING(it.LastName, 1, 1) AS ln", "ln") _
.Select("it.ln AS ln, (SELECT c1.LastName FROM AdventureWorksEntities.Contacts AS c1 " & _
"WHERE SubString(c1.LastName, 1, 1) = it.ln) AS CONTACT").OrderBy("it.ln")
'</snippetComplexQueryBuilderMethod>
' Execute the query and walk through the nested records.
For Each rec As DbDataRecord In query.Execute(MergeOption.AppendOnly)
Console.WriteLine("Last names that start with the letter '{0}':", rec(0))
Dim list As List(Of DbDataRecord) = TryCast(rec(1), List(Of DbDataRecord))
For Each r As DbDataRecord In list
For i As Integer = 0 To r.FieldCount - 1
Console.WriteLine(" {0} ", r(i))
Next
Next
Next
End Using
'</snippetProjection_GroupBy>
End Sub
Public Shared Sub Projection_Union()
Console.WriteLine("Starting method 'Projection_Union'")
'<snippetProjection_Union>
Using context As New AdventureWorksEntities()
Dim query As ObjectQuery(Of DbDataRecord) = _
context.Products.Select("it.Name, it.ProductID As Pid, it.ListPrice") _
.Where("it.Name LIKE 'A%'").Union(context.Products.Select("it.Name, it.ProductID As Pid, it.ListPrice") _
.Where("it.Name LIKE 'B%'")).Select("it.Name, it.ListPrice").OrderBy("it.Name")
For Each rec As DbDataRecord In query
Console.WriteLine("Name: {0}; ListPrice: {1}", rec(0), rec(1))
Next
End Using
'</snippetProjection_Union>
End Sub
Public Shared Sub Projection_Union_LINQ()
'<snippetProjectionUnionLINQ>
Using context As New AdventureWorksEntities()
Dim query = (From a In context.Products Where a.Name.StartsWith("A") _
Select (New With {a.Name, .pid = a.ProductID, a.ListPrice})). _
Union( _
From b In context.Products Where b.Name.StartsWith("B") _
Select (New With {b.Name, .pid = b.ProductID, b.ListPrice})). _
Select(Function(c) New With {c.Name, c.ListPrice}).OrderBy(Function(d) d.Name)
For Each result In query
Console.WriteLine(result.Name)
Next
End Using
'</snippetProjectionUnionLINQ>
End Sub
Public Shared Sub ObjectQuery_Where2()
Console.WriteLine("Starting method 'ObjectQuery_Where2'")
'<snippetObjectQuery_Where2>
Using context As New AdventureWorksEntities()
' Define the product ID for filtering.
Dim productId As Integer = 900
'<snippetObjectQuery_WhereOnly>
' Return Product objects with the specified ID.
Dim query As ObjectQuery(Of Product) = context.Products.Where("it.ProductID = @product", New ObjectParameter("product", productId))
'</snippetObjectQuery_WhereOnly>
' Iterate through the collection of Product items.
For Each result As Product In query
Console.WriteLine("Product Name: {0}; Product ID: {1}", result.Name, result.ProductID)
Next
End Using
'</snippetObjectQuery_Where2>
End Sub
Public Shared Sub ObjectQuery_GroupBy()
Console.WriteLine("Starting method 'ObjectQuery_GroupBy'")
'<snippetObjectQuery_GroupBy>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product " & vbCr & vbLf & " FROM AdventureWorksEntities.Products AS product"
Dim productQuery As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As ObjectQuery(Of DbDataRecord) = _
productQuery.GroupBy("it.name AS pn", "Sqlserver.COUNT(it.Name) as count, pn")
' Iterate through the collection of Products
' after the GroupBy method was called.
For Each result As DbDataRecord In productQuery2
Console.WriteLine("Name: {0}; Count: {1}", result("pn"), result("count"))
Next
End Using
End Sub
'</snippetObjectQuery_GroupBy>
Public Shared Sub ObjectQuery_Except()
Console.WriteLine("Starting method 'ObjectQuery_Except'")
'<snippetObjectQuery_Except>
Dim productID = 900
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
Dim productQuery As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim queryString2 As String = "SELECT VALUE product FROM AdventureWorksEntities.Products " & _
" AS product WHERE product.ProductID < @productID"
Dim productQuery2 As New ObjectQuery(Of Product)(queryString2, context, MergeOption.NoTracking)
productQuery2.Parameters.Add(New ObjectParameter("productID", productID))
Dim productQuery3 As ObjectQuery(Of Product) = productQuery.Except(productQuery2)
Console.WriteLine("Result of Except")
Console.WriteLine("------------------")
' Iterate through the collection of Product items
' after the Except method was called.
For Each result As Product In productQuery3
Console.WriteLine("Product Name: {0}", result.ProductID)
Next
End Using
'</snippetObjectQuery_Except>
End Sub
Public Shared Sub ObjectQuery_Distinct_UnionAll()
Console.WriteLine("Starting method 'ObjectQuery_Distinct_UnionAll'")
'<snippetObjectQuery_Distinct_UnionAll>
Dim productID = 100
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products " & _
" AS product WHERE product.ProductID < @productID"
Dim productQuery As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery3 As ObjectQuery(Of Product) = productQuery.UnionAll(productQuery2)
productQuery3.Parameters.Add(New ObjectParameter("productID", productID))
Console.WriteLine("Result of UnionAll")
Console.WriteLine("------------------")
' Iterate through the collection of Product items,
' after the UnionAll method was called on two queries.
For Each result As Product In productQuery3
Console.WriteLine("Product Name: {0}", result.ProductID)
Next
Dim productQuery4 As ObjectQuery(Of Product) = productQuery3.Distinct()
Console.WriteLine(vbLf & "Result of Distinct")
Console.WriteLine("------------------")
' Iterate through the collection of Product items.
' after the Distinct method was called on a query.
For Each result As Product In productQuery4
Console.WriteLine("Product Name: {0}", result.ProductID)
Next
End Using
'</snippetObjectQuery_Distinct_UnionAll>
End Sub
Public Shared Sub ObjectQuery_Distinct_Union()
Console.WriteLine("Starting method 'ObjectQuery_Distinct_Union'")
'<snippetObjectQuery_Distinct_Union>
Dim productID = 100
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product " & _
" WHERE product.ProductID < @productID"
Dim productQuery As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery2 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
Dim productQuery3 As ObjectQuery(Of Product) = productQuery.Union(productQuery2)
productQuery3.Parameters.Add(New ObjectParameter("productID", productID))
Console.WriteLine("Result of Union")
Console.WriteLine("------------------")
' Iterate through the collection of Product items,
' after the Union method was called on two queries.
For Each result As Product In productQuery3
Console.WriteLine("Product Name: {0}", result.ProductID)
Next
End Using
'</snippetObjectQuery_Distinct_Union>
End Sub
Public Shared Sub LINQQuery_Parameters()
Console.WriteLine("Starting method 'LINQQuery_Parameters'")
'<snippetLINQQuery_Parameters>
Using context As New AdventureWorksEntities()
Dim FirstName = "Frances"
Dim LastName = "Adams"
Dim contactQuery = From contact In context.Contacts _
Where contact.LastName = LastName AndAlso contact.FirstName = FirstName _
Select contact
' Iterate through the results of the parameterized query.
For Each result In contactQuery
Console.WriteLine("{0} {1}", result.FirstName, result.LastName)
Next
End Using
'</snippetLINQQuery_Parameters>
End Sub
Public Shared Sub ObjectQuery_Parameters()
Console.WriteLine("Starting method 'ObjectQuery_Parameters'")
'<snippetObjectQuery_Parameters>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts" & _
" AS contact WHERE contact.LastName = @ln AND contact.FirstName = @fn"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context)
' Add parameters to the collection.
contactQuery.Parameters.Add(New ObjectParameter("ln", "Adams"))
contactQuery.Parameters.Add(New ObjectParameter("fn", "Frances"))
Dim objectParameterCollection As ObjectParameterCollection = contactQuery.Parameters
' Iterate through the ObjectParameterCollection.
For Each result As ObjectParameter In objectParameterCollection
Console.WriteLine("{0} {1} {2}", result.Name, result.Value, result.ParameterType)
Next
End Using
'</snippetObjectQuery_Parameters>
End Sub
Public Shared Sub ObjectQuery_Name()
Console.WriteLine("Starting method 'ObjectQuery_Name'")
'<snippetObjectQuery_Name>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts AS contact"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context, MergeOption.NoTracking)
' Write ObjectQuery's name.
Console.WriteLine("The ObjectQuery's name is: {0}", contactQuery.Name)
End Using
'</snippetObjectQuery_Name>
End Sub
Public Shared Sub ObjectQuery_ScalarTypeException()
Console.WriteLine("Starting method 'ObjectQuery_ScalarTypeException'")
Console.WriteLine("This method should generate an ArgumentException.")
'<snippetObjectQuery_ScalarTypeException>
Using context As New AdventureWorksEntities()
Try
'<snippetObjectQuery_ScalarTypeExceptionShort>
' Define a query projection that returns
' a collection with a single scalar result.
Dim scalarQuery As New ObjectQuery(Of Int32)("100", context)
' Calling an extension method that requires a collection
' will result in an exception.
Dim hasValues As Boolean = scalarQuery.Any()
'</snippetObjectQuery_ScalarTypeExceptionShort>
Catch ex As ArgumentException
Console.WriteLine(ex.ToString())
End Try
End Using
'</snippetObjectQuery_ScalarTypeException>
End Sub
Public Shared Sub ObjectQuery_Context()
Console.WriteLine("Starting method 'ObjectQuery_Context'")
'<snippetObjectQuery_Context>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts AS contact"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context, MergeOption.NoTracking)
' Get ObjectContext from ObjectQuery.
Dim objectContext As ObjectContext = contactQuery.Context
Console.WriteLine("Connection string {0}", objectContext.Connection.ConnectionString)
End Using
'</snippetObjectQuery_Context>
End Sub
Public Shared Sub ObjectQueryConstructors()
Console.WriteLine("Starting method 'ObjectQueryConstructors'")
'<snippetObjectQuery>
Using context As New AdventureWorksEntities()
' Call the constructor with a query for products and the ObjectContext.
Dim productQuery1 As New ObjectQuery(Of Product)("Products", context)
For Each result As Product In productQuery1
Console.WriteLine("Product Name: {0}", result.Name)
Next
Dim queryString As String = "SELECT VALUE product FROM AdventureWorksEntities.Products AS product"
' Call the constructor with the specified query and the ObjectContext.
Dim productQuery2 As New ObjectQuery(Of Product)(queryString, context)
For Each result As Product In productQuery2
Console.WriteLine("Product Name: {0}", result.Name)
Next
' Call the constructor with the specified query, the ObjectContext,
' and the NoTracking merge option.
Dim productQuery3 As New ObjectQuery(Of Product)(queryString, context, MergeOption.NoTracking)
For Each result As Product In productQuery3
Console.WriteLine("Product Name: {0}", result.Name)
Next
End Using
'</snippetObjectQuery>
End Sub
Public Shared Sub ObjectParameterCollectionClass_Remove()
Console.WriteLine("Starting method 'ObjectParameterCollectionClass_Remove'")
'<snippetObjectParameterCollection_Remove>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts " & _
" AS contact WHERE contact.LastName = @ln AND contact.FirstName = @fn"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context)
' Add parameters to the ObjectQuery's Parameters collection.
contactQuery.Parameters.Add(New ObjectParameter("ln", "Adams"))
contactQuery.Parameters.Add(New ObjectParameter("fn", "Frances"))
Dim objectParameterCollection As ObjectParameterCollection = contactQuery.Parameters
Console.WriteLine("Count before Remove is called: {0}", objectParameterCollection.Count)
Dim objectParameter As ObjectParameter = objectParameterCollection("ln")
' Remove the specified parameter from the collection.
objectParameterCollection.Remove(objectParameter)
Console.WriteLine("Count after Remove is called: {0}", objectParameterCollection.Count)
End Using
'</snippetObjectParameterCollection_Remove>
End Sub
Public Shared Sub ObjectParameterCollectionClass_CopyTo()
Console.WriteLine("Starting method 'ObjectParameterCollectionClass_CopyTo'")
'<snippetObjectParameterCollection_CopyTo>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts " & _
" AS contact WHERE contact.LastName = @ln AND contact.FirstName = @fn"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context)
' Add parameters to the collection.
contactQuery.Parameters.Add(New ObjectParameter("ln", "Adams"))
contactQuery.Parameters.Add(New ObjectParameter("fn", "Frances"))
Dim objectParameterCollection As ObjectParameterCollection = contactQuery.Parameters
Dim objectParameterArray As ObjectParameter() = New ObjectParameter(objectParameterCollection.Count - 1) {}
objectParameterCollection.CopyTo(objectParameterArray, 0)
' Iterate through the ObjectParameter array.
For i As Integer = 0 To objectParameterArray.Length - 1
Console.WriteLine("Name: {0} Type: {1} Value: {2}", _
objectParameterArray(i).Name, objectParameterArray(i).ParameterType, objectParameterArray(i).Value)
Next
End Using
'</snippetObjectParameterCollection_CopyTo>
End Sub
Public Shared Sub ObjectParameterCollectionClass_Count_Add_Indexer()
Console.WriteLine("Starting method 'ObjectParameterCollectionClass_Count_Add_Indexer'")
'<snippetObjectParameterCollection_Count_Add_Indexer>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts " & _
" AS contact WHERE contact.LastName = @ln AND contact.FirstName = @fn"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context)
' Add parameters to the collection.
contactQuery.Parameters.Add(New ObjectParameter("ln", "Adams"))
contactQuery.Parameters.Add(New ObjectParameter("fn", "Frances"))
Dim objectParameterCollection As ObjectParameterCollection = contactQuery.Parameters
Console.WriteLine("Count is {0}.", objectParameterCollection.Count)
' Iterate through the ObjectParameterCollection collection.
For Each result As ObjectParameter In objectParameterCollection
Console.WriteLine("{0} {1} {2}", result.Name, result.Value, result.ParameterType)
Next
End Using
'</snippetObjectParameterCollection_Count_Add_Indexer>
End Sub
Public Shared Sub ObjectParameterCollectionClass_ContainsWithParamArg()
Console.WriteLine("Starting method 'ObjectParameterCollectionClass_ContainsWithParamArg'")
'<snippetObjectParameterCollection_ParamArg>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts " & _
" AS contact WHERE contact.LastName = @ln AND contact.FirstName = @fn"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context)
' Create a collection of parameters.
Dim param As New ObjectParameter("ln", "Adams")
contactQuery.Parameters.Add(param)
contactQuery.Parameters.Add(New ObjectParameter("fn", "Frances"))
Dim objectParameterCollection As ObjectParameterCollection = contactQuery.Parameters
' Check whether the specifed parameter is in the collection.
If objectParameterCollection.Contains(param) Then
Console.WriteLine("parameter is here")
Else
Console.WriteLine("parameter is not here")
End If
End Using
'</snippetObjectParameterCollection_ParamArg>
End Sub
Public Shared Sub ObjectParameterCollectionClass_ContainsWithStringArg()
Console.WriteLine("Starting method 'ObjectParameterCollectionClass_ContainsWithStringArg'")
'<snippetObjectParameterCollection_StringArg>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts " & _
" AS contact WHERE contact.LastName = @ln AND contact.FirstName = @fn"
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, context)
' Add parameters to the collection.
contactQuery.Parameters.Add(New ObjectParameter("ln", "Adams"))
contactQuery.Parameters.Add(New ObjectParameter("fn", "Frances"))
Dim objectParameterCollection As ObjectParameterCollection = contactQuery.Parameters
If objectParameterCollection.Contains("ln") Then
Console.WriteLine("ln is here")
Else
Console.WriteLine("ln is not here")
End If
End Using
'</snippetObjectParameterCollection_StringArg>
End Sub
Public Shared Sub ObjectParameterClass_Value_Name_Type()
Console.WriteLine("Starting method 'ObjectParameterClass_Value_Name_Type'")
'<snippetObjectParameter_Value_Name_Type>
Using context As New AdventureWorksEntities()
Dim param As New ObjectParameter("fn", GetType(System.String))
param.Value = "Frances"
Console.WriteLine("Parame Name: {0}, Param Value: {1} Param Type: {2}", _
param.Name, param.Value, param.ParameterType)
End Using
'</snippetObjectParameter_Value_Name_Type>
End Sub
Public Shared Sub ObjectParameterClass()
Console.WriteLine("Starting method 'ObjectParameterClass'")
'<snippetObjectParameter>
Using context As New AdventureWorksEntities()
Dim queryString As String = "SELECT VALUE contact FROM AdventureWorksEntities.Contacts " & _
"AS contact WHERE contact.FirstName = @fn"
Dim param As New ObjectParameter("fn", "Frances")
Dim contactQuery As ObjectQuery(Of Contact) = context.CreateQuery(Of Contact)(queryString, param)
' Iterate through the collection of Contact items.
For Each result As Contact In contactQuery
Console.WriteLine("First Name: {0}, Last Name: {1}", result.FirstName, result.LastName)
Next
End Using
'</snippetObjectParameter>
End Sub
Public Shared Sub EntityKeyClass_TryGetObjectByKey()
Console.WriteLine("Starting method 'EntityKeyClass_TryGetObjectByKey'")
'<snippetEntityKeyClass_TryGetObjectByKey>
Using context As New AdventureWorksEntities()
Dim entity As Object = Nothing
Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("SalesOrderID", 43680)}
' Create the key for a specific SalesOrderHeader object.
Dim key As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues)
' Get the object from the context or the persisted store by its key.
If context.TryGetObjectByKey(key, entity) Then
Console.WriteLine("The requested " & entity.GetType().FullName & " object was found")
Else
Console.WriteLine("An object with this key could not be found.")
End If
End Using
'</snippetEntityKeyClass_TryGetObjectByKey>
End Sub
Public Shared Sub EntityKeyClass_GetObjectByKey_CreateKey()
Console.WriteLine("Starting method 'EntityKeyClass_GetObjectByKey_CreateKey'")
'<snippetEntityKeyClass_GetObjectByKey>
Using context As New AdventureWorksEntities()
Try
' Define the entity key values.
Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("SalesOrderID", 43680)}
' Create the key for a specific SalesOrderHeader object.
Dim key As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues)
' Get the object from the context or the persisted store by its key.
Dim order As SalesOrderHeader = DirectCast(context.GetObjectByKey(key), SalesOrderHeader)
Console.WriteLine("SalesOrderID: {0} Order Number: {1}", order.SalesOrderID, order.SalesOrderNumber)
Catch ex As ObjectNotFoundException
Console.WriteLine(ex.ToString())
End Try
End Using
'</snippetEntityKeyClass_GetObjectByKey>
End Sub