Tài liệu Practical Database Programming With Visual C#.NET- P4 pdf

50 1.2K 0
Tài liệu Practical Database Programming With Visual C#.NET- P4 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

4.4 LINQ to Objects 173 indexes of the contents of a directory tree. A simple string search is performed in this example. However, more complex types of pattern matching can be performed with a regular expression. Create a new C# Console project named QueryContentsLINQ, and then open the code window of this new project and enter the codes shown in Figure 4.28 into the code window of this project. Let ’ s take a closer look at this piece of code to see how it works. A. A string object startFolder is created and the value of this object is the default path of the Visual Studio.NET 2008, in which all fi les of the Visual Studio.NET 2008 are installed. You can modify this path if you installed your Visual Studio.NET 2008 at a different folder in your computer. B. An IEnumerable < T > interface is used to defi ne the data type of the queried fi les fi leList. The real data type applied here is System.IO.FileInfo, which is used to replace the nominal type T. The method GetFiles() is executed to open and access the queried fi les with the fi le path as the argument of this method. C. The query criteria “ Visual Studio ” , which is a keyword to be searched by this query, is assigned to a string object searchTerm that will be used in the following query process. D. The LINQ query is created and initialized with four clauses, from , let , where , and select . The range variable fi le is selected from the opened fi les fi leList. The method GetFileText() will be executed to read back the contents of the matched fi les using the let clause. Two where clauses are used here to fi lter the matched fi les with both an extension .htm and a keyword “ Visual Studio ” in the fi le name. E. The Console.WriteLine() method is executed to indicate that the following matched fi les contain the searched keyword “ Visual Studio ” in their fi le names. F. The LINQ query is executed to pick up all fi les that have a fi le name that contains the keyword “ Visual Studio ” , and all searched fi les are displayed by using the method Console.WriteLine(). G. The purpose of these two coding lines is to allow users to run this project in a Debugging mode. H. The body of the method GetFileText() starts from here. The point is that this method must be defi ned as a static method prefi xed with the keyword static in front of this method since it will be called from the main() method, which is a static method, too. I. The string object fi leContents is initialized with an empty string object. J. The system method Exists() is executed to fi nd all fi les whose names contain the keyword “ Visual Studio ” . All of matched fi les will be opened and the contents will be read back by the method ReadAllText() and assigned to the string object fi leContents. K. The read - out fi leContents object is returned to the calling method. L. The body of the method GetFiles() starts from here with the path as the argument of this method. The point is that this method must be defi ned as a static method and the returned data type is an IEnumerable < T > type. M. An exception will be thrown out if the desired path did not exist in the current computer. N. A new nongeneric collection List < T > is created with a Cast to convert it to the IEnumerable < T > type. O. The system method GetFiles() is executed to fi nd the names of all fi les that are under the current path and assign them to the string object array fi leNames. c04.indd 173c04.indd 173 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 174 Chapter 4 Introduction to Language-Integrated Query (LINQ) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QueryContentsLINQ { class Program { static void Main(string[] args) { // Modify this path as necessary. string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\"; // Take a snapshot of the file system. IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder); string searchTerm = @"Visual Studio"; // Search the contents of each file. The queryMatchingFiles is an IEnumerable<string>. var queryMatchingFiles = from file in fileList where file.Extension == ".htm" let fileText = GetFileText(file.FullName) where fileText.Contains(searchTerm) select file.FullName; // Execute the query. Console.WriteLine("The term \"{0}\" was found in:", searchTerm); foreach (string filename in queryMatchingFiles) { Console.WriteLine(filename); } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit "); Console.ReadKey(); } // Read the contents of the file. static string GetFileText( string name) { string fileContents = String.Empty; // If the file has been deleted since we took the snapshot, ignore it and return the empty string. if (System.IO.File.Exists(name)) fileContents = System.IO.File.ReadAllText(name); return fileContents; } // This method assumes that the application has discovery permissions for all folders under the specified path. static IEnumerable<System.IO.FileInfo> GetFiles(string path) { if (!System.IO.Directory.Exists(path)) throw new System.IO.DirectoryNotFoundException(); string[] fileNames = null; List<System.IO.FileInfo> files = new List<System.IO.FileInfo>(); fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories); foreach (string name in fileNames) { files.Add(new System.IO.FileInfo(name)); } return files; } } } A B C D E F G H I J K L M N O P Q QueryContentsLINQ.Program Main() Figure 4.28 Coding for the example project QueryContentsLINQ. c04.indd 174c04.indd 174 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 4.4 LINQ to Objects 175 P. The foreach loop is executed to add all searched fi le names into the nongeneric collection List< T > object fi les. Q. All of those fi les are returned to the calling method. Now you can build and run the project by clicking the Debug|Start Debugging menu item. All fi les that have the extension .htm, and under the path C:\program fi les\Microsoft Visual Studio 9.0\ and whose name contains the keyword “ Visual Studio ” are found and displayed as this project runs. Press any key on the keyboard to exit this project. A complete C# Console project named QueryContentsLINQ can be found in the folder DBProjects\Chapter 4 located at the accompanying ftp site . Next let ’ s have a dis- cussion about another query related to LINQ to Objects, the LINQ and Refl ection. 4.4.4 LINQ and Refl ection The .NET Framework 3.5 class library refl ection APIs can be used to examine the meta- data in a .NET assembly and create collections of types, type members, parameters, and so on that are in that assembly. Because these collections support the generic IEnumerable interface, they can be queried by using LINQ to Objects query. To make it simple and easy, in this section we use one example project to illustrate how LINQ can be used with refl ection to retrieve specifi c metadata about methods that match a specifi ed search criterion. In this case, the query will fi nd the names of all the methods in the assembly that return enumerable types such as arrays. Create a new C# console project and name it QueryRefl ectionLINQ. Open the code window of this new project and enter the codes shown in Figure 4.29 into this window. Let ’ s take a closer look at this piece of code to see how it works. A. The namespace System.Refl ection is added into the namespace declaration part of this project since we need to use some components defi ned in this namespace in this coding. B. An Assembly object is created with the Load() method and is executed to load and assign this new Assembly to the instance assembly. C. The LINQ query is created and initialized with three clauses. The GetTypes() method is used to obtain the data type of all queried methods. The fi rst where clause is used to fi lter methods in the Public type. The second from clause is used to get the desired methods based on the data type Public. The second where clause is used to fi lter all methods with three criteria: (1) the returning type of the method is array, (2) those methods should have a valid interface, and (3) the returning type of those methods should not be System.,string. Also the queried methods ’ names are converted to string. D. Two foreach loops are utilized here. The fi rst one is used to retrieve and display the data type of the queried methods, and the second one is used to retrieve and display the names of the queried methods. E. The purpose of these two coding lines is to allow users to run this project in a Debugging mode. Now you can build and run the project by clicking the Debug|Start Debugging menu item. The running results are displayed in the console window. A complete C# Console project named QueryRefl ectionLINQ can be found in the folder DBProjects\Chapter 4 located at the accompanying ftp site (see Chapter 1 ). c04.indd 175c04.indd 175 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 176 Chapter 4 Introduction to Language-Integrated Query (LINQ) 4.5 LINQ TO DATASET As we discussed in the previous section, LINQ to DataSet is a subcomponent of LINQ to ADO.NET. The DataSet, of which we provided a very detailed discussion in Chapter 3 , is one of the most widely used components in ADO.NET, and it is a key element of the disconnected programming model upon which ADO.NET is built. Despite this promi- nence, however, the DataSet has limited query capabilities. LINQ to DataSet enables you to build richer query capabilities into DataSet by using the same query functionality that is available for many other data sources. Because the LINQ to DataSet is built on the existing ADO.NET 2.0 architecture, the codes developed by using ADO.NET 2.0 will continue to function in a LINQ to DataSet application without modifi cations. This is a very valuable advantage since any new component has its own architecture and tools with a defi nite learning curve needed in order to understand it. Among all LINQ to DataSet query operations, the following three are most often implemented in most popular applications: 1. Perform operations to DataSet objects. 2. Perform operations to DataRow objects using the extension methods. 3. Perform operations to DataTable objects. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace QueryReflectionLINQ { class Program { static void Main(string[] args) { Assembly assembly = Assembly.Load("System.Core, Version=3.5.0.0, Culture=neutral, “ + “PublicKeyToken= b77a5c561934e089"); var pubTypesQuery = from type in assembly.GetTypes() where type.IsPublic from method in type.GetMethods() where method.ReturnType.IsArray == true || (method.ReturnType.GetInterface(typeof (System.Collections.Generic.IEnumerable<>).FullName) != null && method.ReturnType.FullName != "System.String") group method.ToString() by type.ToString(); foreach (var groupOfMethods in pubTypesQuery) { Console.WriteLine("Type: {0}", groupOfMethods.Key); foreach (var method in groupOfMethods) { Console.WriteLine(" {0}", method); } } Console.WriteLine("Press any key to exit "); Console.ReadKey(); } } } QueryReflectionLINQ.Program Main() A B C D E Figure 4.29 Coding for the example project QueryRefl ectionLINQ. c04.indd 176c04.indd 176 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 4.5 LINQ to DataSet 177 First let ’ s get a deeper understanding of the LINQ to DataSet or the operations to the DataSet objects. 4.5.1 Operations to DataSet Objects Data sources that implement the IEnumerable < T > generic interface can be queried through LINQ using the SQO methods. Using AsEnumerable SQO to query a DataTable returns an object that implements the generic IEnumerable < T > interface, which serves as the data source for LINQ to DataSet queries. In the query, you specify exactly the information that you want to retrieve from the data source. A query can also specify how that information should be sorted, grouped, and shaped before it is returned. In LINQ, a query is stored in a variable. If the query is designed to return a sequence of values, the query variable itself must be an enumerable type. This query variable takes no action and returns no data; it only stores the query information. After you create a query you must execute that query to retrieve any data. In a query that returns a sequence of values, the query variable itself never holds the query results and only stores the query commands. Execution of the query is deferred until the query variable is iterated in a foreach loop. This is called deferred execution; that is, query execution occurs some time after the query is constructed. This means that you can execute a query as often as you want. This is useful when, for example, you have a database that is being updated by other applications. In your application, you can create a query to retrieve the latest information and repeatedly execute the query, returning the updated information every time. In contrast to deferred queries, which return a sequence of values, queries that return a singleton value are executed immediately. Some examples of singleton queries are Count, Max, Average, and First. These execute immediately because the query results are required to calculate the singleton result. For example, in order to fi nd the average of the query results the query must be executed so that the averaging function has input data with which work. You can also use the ToList < TSource > or ToArray < TSource > methods on a query to force immediate execution of a query that does not produce a singleton value. These techniques to force immediate execution can be useful when you want to cache the results of a query. Basically, to perform a LINQ to DataSet query, three steps are needed: 1. Create a new DataSet instance. 2. Populate the DataSet instance using the Fill() method. 3. Query the DataSet instance using LINQ to DataSet. After a DataSet object has been populated with data, you can begin querying it. Formulating queries with LINQ to DataSet is similar to using LINQ against other LINQ - enabled data sources. Remember, however, that when you use LINQ queries over a DataSet object you are querying an enumeration of DataRow objects, instead of an enumeration of a custom type. This means that you can use any of the members of the DataRow class in your LINQ queries. This lets you create rich and complex queries. As with other implementations of LINQ, you can create LINQ to DataSet queries in two different forms: query expression syntax and method - based query syntax. Basically, the query expression syntax will be fi nally converted to the method - based query syntax c04.indd 177c04.indd 177 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 178 Chapter 4 Introduction to Language-Integrated Query (LINQ) as the compiling time if the query is written as the query expression, and the query will be executed by calling the SQO methods as the project runs. 4.5.1.1 Query Expression Syntax A query expression is a query expressed in query syntax. A query expression is a fi rst - class language construct. It is just like any other expression and can be used in any context in which a C# expression is valid. A query expression consists of a set of clauses written in a declarative syntax similar to SQL or XQuery. Each clause in turn contains one or more C# expressions, and these expressions may themselves be either a query expression or contain a query expression. A query expression must begin with a from clause and must end with a select or group clause. Between the fi rst from clause and the last select or group clause, it can contain one or more of these optional clauses: where , orderby , join , let , and even addi- tional from clauses. You can also use the into keyword to enable the result of a join or group clause to serve as the source for additional query clauses in the same query expression. In all LINQ queries (including LINQ to DataSet), all of clauses will be converted to the associated SQO methods, such as From, Where, OrderBy, Join, Let, and Select, as the queries are compiled. Refer to Table 4.1 to get the most often used Standard Query Operators and their defi nitions. In LINQ, a query variable is always strongly typed, and it can be any variable that stores a query instead of the results of a query. More specifi cally, a query variable is always an enumerable type that will produce a sequence of elements when it is iterated over in a foreach loop or a direct call to its method IEnumerator.MoveNext. The code example in Figure 4.30 shows a simple query expression with one data source, one fi ltering clause, one ordering clause, and no transformation of the source elements. The select clause ends the query. An integer array is created here and this array works as a data source. The variable scoreQuery is a query variable, and it contains only the query command and does not static void Main() { // Data source. int[] scores = { 90, 71, 82, 93, 75, 82 }; // Query Expression. IEnumerable<int> scoreQuery = from score in scores //required where score > 80 //optional orderby score descending //optional select score; //must end with select or group // Execute the query to produce the results foreach (int testScore in scoreQuery) { Console.WriteLine(testScore); } } // Outputs: 90 82 93 82 Figure 4.30 Example codes for the query expression syntax. c04.indd 178c04.indd 178 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 4.5 LINQ to DataSet 179 contain any query result. This query is composed of four clauses: from, where, orderby, and select. Both the fi rst and the last clause are required and the others are optional. The query is cast to a type of IEnumerable < int > by using an IEnumerable < T > interface. The testScore is an iteration variable that is scanned through the foreach loop to get and display each queried data when this query is executed. Basically, when the foreach state- ment executes, the query results are not returned through the query variable scoreQuery. Rather, they are returned through the iteration variable testScore. An alternative way to write this query expression is to use the so - called implicit typing of query variables. The difference between the explicit and implicit typing of query variables is that in the former situation, the relationship between the query variable scoreQuery and the select clause is clearly indicated by the IEnumerable < T > interface, and this makes sure that the type of returned collection is IEnumerable < T > , which can be queried by LINQ. In the latter situation, we do not exactly know the data type of the query variable, and therefore an implicit type var is used to instruct the compiler to infer the type of a query variable (or any other local variable) at the compiling time. The example codes written in Figure 4.30 can be expressed in another format as shown in Figure 4.31 by using the implicit typing of query variable. Here the implicit type var is used to replace the explicit type IEnumerable < T > for the query variable, and it can be converted to the IEnumerable < int > automatically as this piece of code is compiled. 4.5.1.2 Method - Based Query Syntax Most queries used in the general LINQ queries are written as query expressions by using the declarative query syntax introduced in C# 3.0. However, the .NET Common Language Runtime (CLR) has no notion of query syntax in itself. Therefore, at compile time, query expressions are converted to something that the CLR can understand — method calls. These methods are SQO methods, and they have names equivalent to query clauses such as Where , Select , GroupBy , Join , Max , Average , and so on. You can call them directly by using method syntax instead of query syntax. In Sections 4.1.3 and 4.1.4 , we provided static void Main() { // Data source. int[] scores = { 90, 71, 82, 93, 75, 82 }; // Query Expression. var scoreQuery = from score in scores //required where score > 80 //optional orderby score descending //optional select score; //must end with select or group // Execute the query to produce the results foreach (var testScore in scoreQuery) { Console.WriteLine(testScore); } } // Outputs: 90 82 93 82 Figure 4.31 Example codes for the query expression in implicit typing of query variable. c04.indd 179c04.indd 179 2/11/2010 11:52:12 AM2/11/2010 11:52:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 180 Chapter 4 Introduction to Language-Integrated Query (LINQ) a very detailed discussion about the Standard Query Operator methods. Refer to that section to get more details for those methods and their implementations. In general, we recommend query syntax because it is usually simpler and more read- able; however, there is no semantic difference between method syntax and query syntax. In addition, some queries, such as those that retrieve the number of elements that match a specifi ed condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls. The reference documentation for the Standard Query Operators in the System.Linq namespace generally uses method syntax. Therefore, even when getting started writing LINQ queries, it is useful to be familiar with how to use method syntax in queries and in query expressions themselves. We have discussed the Standard Query Operator with quite few examples using the method syntax in Sections 4.1.3 and 4.1.4 . Refer to those sections to get a clear picture of how to create and use method syntax to directly call SQO methods to perform LINQ queries. In this section, we just give an example to illustrate the different format using the query syntax and the method syntax for a given data source. Create a new C# console project named QueryMethodSyntax. Open the code window of this new project and enter the codes shown in Figure 4.32 into this code window. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QueryMethodSyntax { class Program { static void Main(string[] args) { int[] numbers = {5, 10, 8, 3, 6, 12}; //Query syntax: IEnumerable<int> querySyntax = from num in numbers where num % 2 == 0 orderby num select num; //Method syntax: IEnumerable<int> methodSyntax = numbers.Where(num => num % 2 == 0).OrderBy(n => n); //Execute the query in query syntax foreach (int i in querySyntax) { Console.Write(i + " "); } Console.WriteLine(System.Environment.NewLine); //Execute the query in method syntax foreach (int i in methodSyntax) { Console.Write(i + " "); } // Keep the console open in debug mode. Console.WriteLine(System.Environment.NewLine); Console.WriteLine("Press any key to exit … "); Console.ReadKey(); } } } A B C D E F QueryMethodSyntax.Program Main() Figure 4.32 Coding for the example project QueryMethodSyntax. c04.indd 180c04.indd 180 2/11/2010 11:52:13 AM2/11/2010 11:52:13 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 4.5 LINQ to DataSet 181 Let ’ s take a close look at this piece of code to see how it works. A. An integer array is created and it works as a data source for this project. B. T h e fi rst query that uses a query syntax is created and initialized with four clauses. The query variable is named querySyntax with a type of IEnumerable < int > . C. The second query that uses a method syntax is created and initialized with the SQO methods Where() and OrderBy(). D. T h e fi rst query is executed using a foreach loop, and the query result is displayed by using the Console.WriteLine() method. E. The second query is executed and the result is displayed, too. F. The purpose of these two coding lines is to allow users to run this project in a Debugging mode. It can be found that the method syntax looks simpler in structure and easy to code compared with the query syntax from this piece of code. In facts, the fi rst query with the query syntax will be converted to the second query with the method syntax as the project is compiled. Now you can build and run the project. You can fi nd that the running result is identi- cal for both syntaxes. A complete C# Console project named QueryMethodSyntax can be found in the folder DBProjects\Chapter 4 located at the accompanying ftp site (see Chapter 1 ). Besides the general and special properties of query expressions discussed above, the following points are also important in understanding query expressions: 1. Query expressions can be used to query and to transform data from any LINQ - enabled data source. For example, a single query can retrieve data from a DataSet and produce an XML stream as output. 2. Query expressions are easy to master because they use many familiar C# language constructs. 3. The variables in a query expression are all strongly typed, although in many cases you do not have to provide the type explicitly because the compiler can infer it if an implicit type var is used. 4. A query is not executed until you iterate over the query variable in a foreach loop. 5. At compile time, query expressions are converted to SQO method calls according to the rules set forth in the C# specifi cation. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise. 6. As a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary. There is no semantic or performance dif- ference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax. 7. Some query operations, such as Count or Max, have no equivalent query expression clause and must therefore be expressed as a method call. Method syntax can be combined with query syntax in various ways. 8. Query expressions can be compiled to expression trees or to delegates, depending on the type to which the query is applied. IEnumerable < T > queries are compiled to delegates. IQueryable and IQueryable < T > queries are compiled to expression trees. c04.indd 181c04.indd 181 2/11/2010 11:52:13 AM2/11/2010 11:52:13 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 182 Chapter 4 Introduction to Language-Integrated Query (LINQ) Now let ’ s start the LINQ to DataSet with the single table query. 4.5.1.3 Query the Single Table Language - Integrated Query queries work on data sources that implement the IEnumerable < T > interface or the IQueryable interface. The DataTable class does not implement either interface, so you must call the AsEnumerable method if you want to use the DataTable as a source in the From clause of a LINQ query. As we discussed in Section 4.5.1 , to perform LINQ to DataSet query, the fi rst step is to create an instance of the DataSet and fi ll it with the data from the database. To fi ll a DataSet, a DataAdapter can be used with the Fill() method attached to that DataAdapter. Each DataAdapter can only be used to fi ll a single DataTable in a DataSet. In this section, we show readers an example to query a single DataTable using the LINQ to DataSet. Create a new C# console project and name it DataSetSingleTableLINQ. Open the code window of this new project and enter the codes shown in Figure 4.33 . Let ’ s take a closer look at this piece of code to see how it works. using System; using System.Data; using System.Data.OleDb; using System.Linq; namespace DataSetSingleTableLINQ { class Program { static void Main(string[] args) { string cmdString = "SELECT * FROM Faculty"; OleDbDataAdapter dataAdapter = new OleDbDataAdapter(); OleDbConnection accConnection = new OleDbConnection(); OleDbCommand accCommand = new OleDbCommand(); DataSet ds = new DataSet(); string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + //modify this based on your appl. "Data Source=C:\\database\\Access\\CSE_DEPT.accdb;"; accConnection = new OleDbConnection(connString); accConnection.Open(); accCommand.Connection = accConnection; accCommand.CommandType = CommandType.Text; accCommand.CommandText = cmdString; dataAdapter.SelectCommand = accCommand; dataAdapter.Fill(ds, "Faculty"); var facultyinfo = (from fi in ds.Tables["Faculty"].AsEnumerable() where fi.Field<string>("faculty_name").Equals("Ying Bai") select fi); foreach (var fRow in facultyinfo) { Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}", fRow.Field<string>("title"), fRow.Field<string>("office"), fRow.Field< string>("phone"), fRow .Field<string>("college"), fRow.Field<string>("email")); } accConnection.Close(); } } } A B C D E F G H I DataSetSingleTableLINQ.Program Main() Figure 4.33 Coding for the example project DataSetSingleTableLINQ. c04.indd 182c04.indd 182 2/11/2010 11:52:13 AM2/11/2010 11:52:13 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Depending on how you use this sample database in this project, different databases should be opened If you integrate this database with your project, the database file CSE_ DEPT.mdf should be located at the folder C:\Book 6\Chapter 4\QueryLINQSQL\ QueryLINQSQL\bin\Debug If you did not integrate this database with your project, the database file should be located at the folder C: \database\ SQLServer You need to... the Object Relational Designer The database used in this project is CSE_DEPT.mdf, and it is located in the folder C: \database\ SQLServer Open the Server Explorer window and add this database by right clicking on the Data Connections item and select Add Connection 4 We need to create five entity classes and each of them is associated with a data table in our sample database Drag each table from the Server... } } Figure 4.37 Coding for the example project TypedDataSetLINQ D The new instance of DataSet is populated with data using the Fill() method Basically only the Faculty table is filled with data obtained from the Faculty table in our sample database CSE_DEPT E The LINQ to DataSet query is created with three clauses The data type of the query variable is an implicit data type var, and it can be inferred... CSE_DEPTDataContext are declared in this file Now we need to connect our sample SQL Server database CSE_DEPT to this project using the DataContext object You can open our sample database file CSE_DEPT.mdf from the Server Explorer window if you connected this database to our project before Otherwise you must add a new connection to our sample database To do that, open the Server Explorer if it is not opened by going... after removing an old version of Microsoft SQL Server database by using the Advanced setup function (click on the Advanced button) Otherwise you do not need to do this setup action Another point is that you can find our sample database CSE_DEPT.mdf in the folder Database\ SQLServer located at the accompanying ftp site (see Chapter 1) You can copy this database file and save it to any folder in your computer... data source with objects that share a common attribute in another data source, such as a faculty_id in the LogIn table and in the Faculty table In object-oriented programming, relationships between objects are relatively easy to navigate because each object has a member that references another object In external database tables, however, navigating relationships is not as straightforward Database tables... which is shown in Figure 4.36a Make sure that the Data source box contains Microsoft Access Database File and click on the Browse button to locate the folder in which our sample database file CSE_ DEPT.accdb is located In this application, it is C: \database\ Access Browse to this folder and select our sample database file CSE_DEPT.accdb and click the Open button Your finished Add Connection dialog box... should be located at the folder C: \database\ SQLServer You need to go to the folder in which you stored this sample database file if you save it in any other location Open the Microsoft SQL Server Management Studio Express and expand the Databases folder to find your database Then expand your database to locate all data tables by expanding the Tables folder Right-click on a data table and select the Open... are using a typed DataSet, we can directly use the table name, Faculty, after the DataSet without worry about the Field setup with the real table name F The foreach loop is executed to perform this query, and each queried column from the Faculty table is displayed using the Console.WriteLine() method Compared with the same displaying operation in Figure 4.33, you can find that each column in the queried... value is null Now let’s create a new C# console project to illustrate how to use the Field() method to retrieve some of columns’ values from the DataRow object The database we will use is still our sample Access 2007 database CSE_DEPT.accdb Open Visual Studio.NET 2008 and create a new C# project and name it DataRowFieldLINQ Open the code window of this new project and enter the code shown in Figure 4.38 . of the Visual Studio.NET 2008, in which all fi les of the Visual Studio.NET 2008 are installed. You can modify this path if you installed your Visual Studio.NET. compared with the query syntax from this piece of code. In facts, the fi rst query with the query syntax will be converted to the second query with the

Ngày đăng: 26/01/2014, 08:20

Từ khóa liên quan

Mục lục

  • Practical Database Programming With Visual C#.NET

    • Contents

    • Preface

    • Acknowledgment

    • 1 Introduction

      • Outstanding Features of the Book

      • Target Audience

      • Topics Covered

      • Organization of the Book and How to Use It

      • How to Use the Source Code and Sample Databases

      • Instructor and Customer Support

      • Homework Solutions

      • 2 Introduction to Databases

        • 2.1 What Are Databases and Database Programs?

          • 2.1.1 File Processing System

          • 2.1.2 Integrated Databases

          • 2.2 Develop a Database

          • 2.3 Sample Database

            • 2.3.1 Relational Data Model

            • 2.3.2 Entity-Relationship Model (ER)

            • 2.4 Identifying Keys

              • 2.4.1 Primary Key and Entity Integrity

              • 2.4.2 Candidate Key

              • 2.4.3 Foreign Keys and Referential Integrity

              • 2.5 Define Relationships

                • 2.5.1 Connectivity

                • 2.6 ER Notation

Tài liệu cùng người dùng

Tài liệu liên quan