1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft ADO .NET 4 Step by Step - p 37 ppt

10 71 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 487,66 KB

Nội dung

336 Microsoft ADO.NET 4 Step by Step The Designer adds a .dbml file to your project, which hosts the data model in XML form. It also adds two support files: (1) a .dbml.layout file that stores some designer-specific informa- tion; and (2) a .designer.vb or .designer.cs file that holds the generated entity classes in either Visual Basic or C#. The Designer produces the designer file content as you make content- related changes to the visual design. You build your data model by dragging classes (entities) and associations (relationships) to the left pane of the designer surface. These entity and relationship instances are either generic forms from the Visual Studio Toolbox or existing database elements from the Server Explorer (or Database Explorer in Visual Studio Express Editions) tool window, as shown in Figure 20-1. You can also include database-level stored procedures and custom functions in the model by dragging them to the Designer’s right-side pane. FIGURE 20-1 The Designer after dragging and dropping an existing database table. Any changes you make to the model result in an immediate adjustment to the generated language-specific source code. You should not customize these generated class files because any future changes to the model will overwrite your changes. Note You can generate both the XML model and the class layer from a source database with- out using the visual designer. The Windows SDK installed with Visual Studio includes a program named SqlMetal.exe. This tool generates output similar to that of the visual designer, but it does so through a command-line interface. See the “SqlMetal.exe (Code Generation Tool)” entry in the Visual Studio online help for information on using this application. Chapter 20 Using LINQ to SQL 337 Building a LINQ to SQL Model 1. Open the “Chapter 20 CSharp” (C#) or “Chapter 20 VB” (Visual Basic) project from the installed samples folder. The project includes three Windows.Forms classes: OrderViewer, StatesByYear, and Switchboard. 2. Add a new LINQ to SQL data model to the application through the Project | Add New Item menu command. When the Add New Item form appears, select LINQ to SQL Classes from the list of templates and enter SalesOrder.dbml in the Name field. Click the Add button. 3. Visual Studio displays a blank Object Relational Designer. Open the Server Explorer (or Database Explorer) tool window (use the View | Server Explorer or View | Database Explorer menu if the window is not already present in Visual Studio) to display the contents of the book’s sample database. If the sample database is not already present in the Data Connections tree, use the Connect To Database toolbar button within the Server Explorer to locate the database. 4. Expand the sample database tree in the Server Explorer and drag the following items to the left half of the O/R Designer surface: Customer, OrderEntry, and StateRegion. 338 Microsoft ADO.NET 4 Step by Step As you drag each item, the Designer automatically creates associations between the entities based on foreign key references defined in the database schema. Click each en- tity and association, and then view the Properties panel to review the different settings associated with each element. 5. Drag the AdmittedI nYear custom function from the Server Explorer tree to the right half of the designer surface. This adds a reference to a database-level function, allowing it to be used in your LINQ to SQL queries. Chapter 20 Using LINQ to SQL 339 6. Save changes to the file and close it. The Designer has already generated the class layer for the database objects dragged to the design surface. You can view the generated content by opening SalesOrder.designer.cs (C#) or SalesOrder.designer.vb (Visual Basic, although you may need to click the Show All Files button in the Solution Explorer to see the file). Using Custom Database Functions in Queries Although custom functions defined within a .NET application cannot participate directly in a LINQ to SQL query, these same queries can easily access functions written at the database level. When dragged to the design surface (as was done in the example shown previously), these T-SQL functions become part of the context that also hosts the entity classes. LINQ to Entities includes a similar feature, but it requires you to create local .NET stubs in your own code. With LINQ to SQL, the functions are ready to use in your queries; simply ref- erence the function name as a member of the instantiated context, passing the appropriate parameters as defined within the database. C# // Assumes an AgedInvoices database function that // accepts a customer ID and a number of days, // returning a financial amount. var result = from cu in context.Customers orderby cu.FullName select new { cu.ID, cu.FullName, context.AgedInvoices(cu.ID, 90) }; Visual Basic ' Assumes an AgedInvoices database function that ' accepts a customer ID and a number of days, ' returning a financial amount. Dim result = From cu In context.Customers Select cu.ID, cu.FullName, context.AgedInvoices(cu.ID, 90) Order By cu.FullName You can also call these functions directly, as long as a valid context exists. C# decimal pending = context.AgedInvoices(whichCustomer, 90); Visual Basic Dim pending As Decimal = context.AgedInvoices(whichCustomer, 90) 340 Microsoft ADO.NET 4 Step by Step Querying with LINQ to SQL: C# Note This exercise parallels exercises found in Chapter 19. The project is nearly identical in func- tionality and purpose, but it uses LINQ to SQL instead of LINQ to Entities to process database content. This exercise continues the previous exercise in this chapter. 1. Open the source code view for the General class. Locate the GetConnectionString func- tion; this is a routine that uses a SqlConnectionStringBuilder to create a valid connection string to the sample database. It currently includes the following statements: sqlPortion.DataSource = @"(local)\SQLExpress"; sqlPortion.InitialCatalog = "StepSample"; sqlPortion.IntegratedSecurity = true; Adjust these statements as needed to provide access to your own test database. 2. Open the source code view for the StatesByYear form. This form will access the AdmittedInYear database function, which was dragged into the model in the prior example. 3. Locate the StatesByYear_Load event handler; this is a routine that loads the data onto the form. Add the following code as the body of the routine: using (SalesOrderDataContext context = new SalesOrderDataContext(GetConnectionString())) { var result = from st in context.StateRegions where st.Admitted != null orderby st.Admitted.Value.Year select new { StateName = st.FullName, AdmitYear = st.Admitted.Value.Year, TotalAdmittedInYear = context.AdmittedInYear(st.Admitted) }; StateAdmittance.DataSource = result.ToList(); } In addition to calling the custom function AdmittedInYear, this query also uses != null as a condition, which will translate into the appropriate T-SQL comparison clause. 4. Run the program. When the Switchboard form appears, click States By Year. When the StatesByYear form appears, the results of the query will display in the form’s main grid. Chapter 20 Using LINQ to SQL 341 Querying with LINQ to SQL: Visual Basic Note This exercise parallels exercises found in Chapter 19. It is nearly identical in functionality and purpose, but it uses LINQ to SQL instead of LINQ to Entities to process database content. This exercise continues the previous exercise in this chapter. 1. Open the source code view for the General class. Locate the GetConnectionString func- tion; this is a routine that uses a SqlConnectionStringBuilder to create a valid connection string to the sample database. It currently includes the following statements: sqlPortion.DataSource = "(local)\SQLExpress" sqlPortion.InitialCatalog = "StepSample" sqlPortion.IntegratedSecurity = True Adjust these statements as needed to provide access to your own test database. 2. Open the source code view for the StatesByYear form. This form will access the AdmittedInYear database function, which was dragged into the model in the prior example. 342 Microsoft ADO.NET 4 Step by Step 3. Locate the StatesByYear_Load event handler; this is a routine that loads the data onto the form. Add the following code as the body of the routine: Using context As New SalesOrderDataContext(GetConnectionString()) Dim result = From st In context.StateRegions Where st.Admitted IsNot Nothing Select StateName = st.FullName, AdmitYear = st.Admitted.Value.Year, TotalAdmittedInYear = context.AdmittedInYear(st.Admitted) Order By AdmitYear StateAdmittance.DataSource = result.ToList End Using In addition to calling the custom function AdmittedInYear, this query also uses IsNot Nothing as a condition, which will translate into the appropriate T-SQL comparison clause. 4. Run the program. When the Switchboard form appears, click States By Year. When the StatesByYear form appears, the results of the query will display in the form’s main grid. Chapter 20 Using LINQ to SQL 343 Summary This chapter introduced the LINQ to SQL query provider. Although it shares many features with LINQ to Entities, its quick setup and close ties to SQL Server make it a useful choice for applications that target that platform. LINQ to SQL sports its own visual designer: the Object Relational Designer, or O/R Designer. For developers looking for a more direct approach or who need the automation support available through command-line utilities, the provider also includes SqlMetal.exe as an alter- native to the visual experience. Chapter 20 Quick Reference To Do This Include an entity class in a LINQ query Add the entity class to your project by writing its code, using the Object Relational Designer, or employing the SqlMetal.exe command-line tool. Create a DataContext instance for the generated entity class. Use the context’s exposed entity collections within the From clauses of a LINQ query. Include a custom SQL Server function within a LINQ to SQL query Drag the function to the right half of the Object Relational Designer surface or use equivalent code-based alternatives. Create a DataContext instance that contains the function. Call the function within a LINQ query. Microsoft ADO.NET 4 Step by Step 345 Part V Presenting Data to the World Chapter 21: Binding Data with ADO.NET Chapter 22: Providing RESTful Services with WCF Data Services . the appropriate T-SQL comparison clause. 4. Run the program. When the Switchboard form appears, click States By Year. When the StatesByYear form appears, the results of the query will display. the appropriate T-SQL comparison clause. 4. Run the program. When the Switchboard form appears, click States By Year. When the StatesByYear form appears, the results of the query will display. database function, which was dragged into the model in the prior example. 342 Microsoft ADO. NET 4 Step by Step 3. Locate the StatesByYear_Load event handler; this is a routine that loads the

Ngày đăng: 05/07/2014, 19:20