(Language Integrated Query) The main Topics in this lecture are: What is LINQ? Main Advantages of LINQ. Working with LINQ in ASP.Net Introduction: Suppose you are writing an application using.net. Chances are high that at some point you ll need to persist objects to a database, query the database and load the results back into objects. The problem is that in most cases, at least with relational databases, there is a gap between your programming language and the database. Good attempts have been made to provide object-oriented databases, which would be closer to object-oriented platforms and imperative programming languages like C# and VB.NET. However, after all these years, relational databases are still pervasive and you still have to struggle with data-access and persistence in all of your programs. The original motivation behind LINQ was to address the impedance mismatch between programming languages and databases. With LINQ, Microsoft s intention was to provide a solution for the problem of object-relational mapping, as well as simplify the interaction between objects and data sources. LINQ eventually evolved into a general-purpose languageintegrated querying toolset. This toolset can be used to access data coming from inmemory objects (LINQ to Objects), databases (LINQ to SQL), XML documents (LINQ to XML), a file-system, or from any other source. Advantages of LINQ The big question at this point is: why would we like, in the first place, to have a tool that makes working with programming languages, relational data and XML at the same time more convenient? At the origin of the LINQ project is a simple fact: How many applications access data or talk to a SQL database? The answer: the vast majority of them! Most applications deal with relational databases. Consequently, in order to program applications, learning a language like C# is not enough. You also have to learn SQL and the APIs that tie together 1
C# and SQL to form your full application. We ll start by taking a look at a piece of dataaccess code that uses the standard.net APIs. This will allow us to point out the common problems that are encountered in this kind of code. We will then extend our analysis to a higher level by showing how these problems exist with other kinds of data such as XML. You ll see that LINQ addresses a general impedance mismatch between data sources and programming languages. Finally a piece of short code sample will give you a glimpse at how LINQ is a solution to the problem. LINQ as Language Extensions LINQ allows you to access databases, XML documents and many other data sources by writing queries against these data sources. Rather than being simply syntactic sugar2 that would allow you to easily include SQL queries right into your C# code, LINQ provides you with the same expressive capabilities SQL offers but for your programming language. This is great because a declarative approach like the one LINQ offers allows writing code that is shorter and to the point. Getting Started with LINQ in Visual Studio Environment This next set of steps to get you started requires Visual Studio 2008. If you are using one of the Express versions of Visual Studio, be sure that any add-ons for LINQ are in place. Also, you will need to: 1. Open a new Web Site, and name it ShowLinq. 2. Open Solution Explorer and rename Default.aspx to ShowLinq.aspx. 3. Rename _Default to DoLinq in the C# script, and have it rename the ASP.NET inherit (inherits DoLinq). 4. Right-click the App_Data folder and select Add New Item. 5. Under Templates select SQL Server Database, and in the Name window change the default name to ServiceReg.mdf as shown in Figure 1. Click the Add button when finished. 6. Open the Server Explorer and you should see ServiceReg.mdf among the databases. 2
Right-click the Tables folder icon, and select Add New Table as shown in Figure 2. 7. When the table window opens, add the information shown in Figure 3. RegID is a primary key field and an identity field, so values enter automatically. 8. Save the table using the name RegClients. You will see the table listed in the Tables folder of the ServiceReg.mdf database in the Server Explorer. Figure 1 Selecting SQL database Figure 2: Setting the fields in a new table 3
Figure 3: Setting the fields in a new table 9. Right-click the RegClients table and select Show Table Data. The first time takes a little while. You will see the five fields you created. Click in the first field and press TAB to move to the LastName field. Begin entering records in this second field because the first field automatically enters values. Add about five records to have something to work with. Figure 4 shows an example. (Whenever you make changes in a record, the ReqID changes, so some of the ReqID values are out of sequence in Figure 4.) 10. In the Solution Explorer right-click the site (C:\..ShowLinq\), select Add ASP.NET Folder, and select App_Code. You will now see a new App_Code folder in the Solution Explorer. 11. Right-click the App_Code folder and select Add New Item. Select LINQ To SQL Classes, and in the Name window change the default name to RegClients.dbml and click Add. Figure 5 shows the correct settings Figure 4 Sample records 4
Figure 5 Adding the LINQ to SQL Classes template 12. After you click Add, a double window opens. This is the Object Relational Designer. Drag the RegClients table from the Server Explorer into the right window as shown in Figure 6. 13. From the Solution Explorer open the ShowLinq.aspx file. Then from the Toolbox Data menu drag a LinqDataSource control and drop it inside the <div> container. Switch to the Split mode or to Design mode. Figure 6 Dragging the table into the Object Relational Designer 5
14. Click the LinqDataSource object and open the Properties window. Next to ContextTypeName, select RegClientsDataContext as shown in Figure 7. 15. Set the TableName property to RegClients and the AutoPage property to True. Figure 7 Setting the ContextTypeName property 16. Set the following LinqDataSource1 properties to True: EnableDelete EnableInsert EnableUpdate 17. From the Toolbox Data menu, drag a DetailsView control beneath the LinqDataSource object as shown in Figure 8. 6
Figure 8 Adding the DetailsView control 18. Select the DetailsView control and in the Properties window select the LinqDataSource1 as the DataSourceID as shown in Figure 9. 19. Widen the DetailsView control, and then in the Properties window set the following to True: AutoPage AutoGenerateDeleteButton AutoGenerateEditButton AutoGenerateInsertButton 20. Once you have the settings complete, press CTRL-F5 to test the application. Figure 10 shows what you should see. Figure 9 Setting the DetailsView control DataSourceID property to LinqDataSource1 7
Figure 10 A LINQ-supported application Figure 11 Inserting a new record 21. To test the functionality of the application, click New and add a record as shown in Figure 11. Do not type anything into the RegID field because that is automatically filled. Once you ve finished, click Insert and your new record is added. All of those steps generated very little ASP.NET code. In looking at the ASP.NET portion of the application, all that you will see is shown in the following listing: ASP.NET ShowLinq.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowLinq.aspx.cs" Inherits="DoLinq" %> 8
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>asp.net Linq</title> </head> <body> <form id="form1" runat="server"> <div> <asp:linqdatasource ID="LinqDataSource1" runat="server" ContextTypeName="RegClientsDataContext" EnableDelete="True" EnableInsert="True" EnableUpdate="True" TableName="RegClients"> Figure 14-11 Inserting a new record Chapter 14: LINQ 365 </asp:linqdatasource> <asp:detailsview ID="DetailsView1" runat="server" DataSourceID="LinqDataSource1" AllowPaging="True" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateInsertButton="True" DataKeyNames="RegID" Height="50px" Width="205px"> </asp:detailsview> </div> </form> </body> 9