Microsoft released Visual Studio 2008 (project Orcas) Beta 2 in July this
year, which incorporates .NET Framework 3.5. This new framework adds support for
new Web protocols to build WCF (Windows Communication Foundation) services and
also provides support for WPF (Windows Presentation Foundation). The other
noticeable feature is LINQ, which we will talk about in detail.
LINQ and its features
Language Integrated Query, LINQ, allows standard query operations to be
integrated onto the .NET platform so as to provide a unified way to query across
objects, database, and XML in a standard way. LINQ offers compile-time syntax
checking, rich metadata, and Visual Studio's IntelliSense, which were earlier
available with only .NET code. As LINQ is now part of .NET Framework, it allows
for standard query operators to traverse, filter, and update using any .NET
language programming. The standard query operators allow queries to be applied
to IEnumerable based information source and allow developers to use query style
syntaxes (LINQ expressions) for their codes referring to objects or datasets.
The standard query operators are used for LINQ to Objects as well, where they
can be applied to all in-memory information. The power of LINQ is in its
extensibility. LINQ can provide implementations that work over SQL data sources.
LINQ to SQL translates LINQ-based queries into SQL database queries. A
database-specific provider then analyses and transforms these into appropriate
query language for the data store, for example, Microsoft SQL Server. Let's see
how LINQ can be used over Objects in projects and also over SQL for a database
reference.
Direct Hit! |
Applies To: .NET developers USP: Programming in query style Primary Link: msdn2.microsoft .com/hi-in/vstudio/aa700831.aspx Keywords: Orcas, LINQ, LINQ to SQL |
LINQ to Objects
LINQ to Objects refers to LINQ expressions used for in-memory objects such
as arrays or datasets. To see Language Integrated Query at work, let's create a
new project in Visual Studio 2008. Go to File>New Project and under Project Type
select Visual Basic's Windows project of type Windows Form Application and name
it as LinqDemo1, with this Form1.vb gets created. In the following example we
will try populating a DataGridView with information on files in a directory:
'E:/docs' in our case. First drop a DataGridView from Toolbox pane onto the
Form1 and dock it onto the parent container. Double clicking on the Form1 will
show the code window, where on Form Load event we will first try retrieving the
file information of the directory E:/docs. Using LINQ, we will now write code in
query format to retrieve the file information. The following code snippet does
the same; the file info will be retrieved for the directory and stored in
'files' variable.
Dim files = From file In
My.Computer.FileSystem.GetFiles("E:\docs") Order By file Select file
The LinqDemo example lists the file information in directory 'E:/docs' upon execution of application |
The variable 'files' would contain IEnumerable of String objects. The
compiler automatically gets to know the type of result the query would return.
And the variable is automatically type-casted according to returned result, thus
variable would be having all the file names from the directory. Once we have the
file names, we would now display file information on DataGridView as a list. For
this we will again use FileSystem to get the file information. With GetFileInfo
of FileSystem we get all the attributes related to a file, like name, creation
time, size etc. If we were not to use LINQ here, it would have required getting
a Collection of FileInfo objects and then using loop we would have retrieved
values to store into an array. With query-based coding, a developer can use LINQ
to traverse and retrieve objects. The following code snippet will return an
IEnumerable of FileInfo objects and then we can populate the DataGridView by
passing the filesInfo to list the result.
Dim filesInfo = From file In files Select
My.Computer.FileSystem.GetFileInfo(file)
Me.DataGridView1.DataSource = filesInfo.ToList()
Now, on running the project we can have the list of files along with the
information listed in the DataGridView. With this we show how LINQ over objects
in memory is used and how coding has become easier for the developers with the
standard query operators traversing and retrieving over list of objects
Select the 'User' object, mapped to the table User, in database to set it as the datasource for the project |
LINQ to SQL
We have seen how standard query operators can be used to access in-memory
objects for a .NET project using LINQ. Now LINQ to SQL is also a component of
Visual Studio 2008. It provides a platform for managing relational data as
objects coupled with the ability to use query. In LINQ to SQL, the data model of
a relational database is mapped to a developer-defined object model. When this
is executed, LINQ to SQL translates the language-integrated queries into SQL for
execution by the database, and then returns the results to the defined objects.
This provides an ability to work on and manipulate the objects while LINQ to SQL
working in the background tracks the changes and reflects them onto the
database.
Let's create a new VB project in Visual Studio 2008 to see how LINQ to SQL
works. For this create a new Windows Form Application project and name it as
'Linq2SqlDemo.' For LINQ to SQL we have objects mapped to database entities.
These objects can be simple business classes having attributes that correspond
to columns in the database. But with Visual Studio 2008, we can use O-R Designer
to create these objects that map to the database. To do this first we need to
add LINQ to SQL classes template to the project, which is done by right-clicking
the project name on the Solution Explorer window and selecting the Add > New
Item option. On the Add New Item window name it as PcqDemo.dbml. On clicking
'OK' the object relation designer opens up. Through the Server Explorer window,
select an SQL Server database. For this we have a demo database added to the
Data Connections. For displaying the list of users from the table 'Users,'
drag-drop the table from the data connection onto the O-R Designer. This creates
'Users' object corresponding to the table 'Users' with each property mapping to
the corresponding attribute in the database. This creates a LINQ to SQL class
that connects to the database; from Properties we can see it named as
PcqDemoDataContext. Now we can use this class on our application to access and
manipulate the data in the database.
O-R Designer creates the User object and names the DataContext for Database as PcqDemoDataContext, as shown in Properties window |
Coming back to the form design view we now have to add a data-source to the
project. Here select an Object instead of a Database, something contrary to what
we used to do earlier. On the object-binding window select the 'User' object
under the Project tree. This results in User object being created as data source
with all the attributes. Dropping the User object on the form results in
creating Binding Navigator; now dock the User Binding Navigator to parent
container. On the Form load event write the code that will fetch the list from
the Users table and display it on the Binding Navigator. For this get access to
Data Context, which in our case is PcqDemoDataContext, and we can declare that
globally as follows:
Private Db_con As New PcqDemo3DataContext
Now let's write a query to list the users from the database. We will use LINQ
query on user object that is mapped to the database with the following code
snippet:
Dim showUsers = From user In Db_con.users Order By
user.username Select user
Me.UserBindingSource.DataSource = showUsers
We need not make database connections, but a reference to the DataContext
that will do the mapping of the objects to the database. The query written in
LINQ at compile time gets translated to SQL query so that the database can
execute it and return the result of the query in an object-defined form. The
LINQ feature is easy to start up with, and the LINQ to SQL feature enables the
developer to do common database-related tasks with ease and reduces their work
on coding.
Dragging DataSource User onto Form creates its BindingSource and its Navigator, the result shows the User list ordered by attribute username |