So far we've laid the foundation for our project, and now
it's time to fetch some data. Believe it or not, the hard part is over.
If we were using ADO.NET, we'd have to create a Database
object, or a connection of some form. In LINQ, we create a DataContext
instead. The properties for a DataContext are set from the database connection
and the views we added above. The data context is automatically named with the
name of the DBML file (in my case, Products), with “Data Context” at the end.
In my case, this would give me a name of ProductsDataContext.
Working back in Module1.vb, we instantiate a data context as
shown below. As you type the following line of code, you'll see we have full
Intellisense with our data context.
Listing 1
Sub Main()
Dim _db As New ProductsDataContext
End Sub
Figure 6
So far, so good. Now, let's get some data. Again, as you
type the new line of code, you'll see we have full Intellisense.
Listing 2
Sub Main()
Dim _db As New ProductsDataContext
Dim _products = From p In _db.vProductModelCatalogDescriptions Select p
End Sub
Figure 7
The first difference you see is that we don't declare a type
for _products. We declare _products as an “anonymous type”, which is a new
addition to the Visual Basic language in .NET 3.5. Anonymous types are not variants
with no known type, but are instead objects whose types are inferred
automatically by the compiler. As we develop, the compiler is working in the
background to update these objects, and make the methods and properties
available to us via Intellisense. If you really, really wanted to declare a
type, you could use the following line of code instead:
Listing 3
Dim _products As IQueryable(Of vProductModelCatalogDescription) _
= From p In _db.vProductModelCatalogDescriptions Select p
_products is now an IQueryable object of type
vProductModelCatalogDescription. If you try this, you'll see that once again,
we have full Intellisense. LINQ objects are first class objects, whose exact
type, methods and properties are determined automatically by the compiler.
The second difference you'll notice is how similar to SQL
the LINQ syntax is. This new syntax is very powerful, and yet very simple.