Using strongly typed data in VS2005 and asp.net2.0

Source: Internet
Author: User
Tags date datetime implement query visual studio advantage
asp.net| data First, Introduction

As a developer, when we are learning new technologies, examples may be our biggest enemies. Tutorials are often designed to be easy to understand, but at the same time they often reinforce lazy, inefficient, and even dangerous coding habits. There is no better explanation for the problem than the ado.net example. In this article, we will be ready to analyze the significance of strongly typed objects for your database development and why you should use strongly typed objects in your application without an example.

Specifically, we will analyze how strongly typed datasets are created and used in Visual Studio 2005. As discussed in this article, strongly typed datasets offer many advantages over other, weakly typed data access technologies, and with Visual Studio 2005, it is easier to create and use strongly typed datasets than ever before.

   two, strong type Object Foundation and merit

To understand the meaning of the strongly typed, let's consider the example of a date first. If you are a bachelor, what kind of person do you expect to date? You may already have your own specific criteria, such as being rich and attractive or perhaps living in a superior and sexy environment. No matter what your condition, when you decide who you want to spend more time with, you will inevitably have a set of dating standards. If you're smart, you can make a list of carefully thought-out lists that can help you save unnecessary emotional effort. Adding a "non-alcoholic" condition to your dating criteria will save you a lot of time and allow you to spend your time and energy on dating better candidates.

You may wonder, how can this be compared to programming? Please listen to my explanation. Ado. NET data Access object is designed to achieve maximum flexibility. Unless you get into a lot of trouble, when you read data from a database, you use a lot of ordinary, untyped objects--of course. NET Framework is fully permitted to do so. Using our dating analogy, always treating your relational data as a generic object is a bit like admitting, "I only date people who meet my criteria." Can't you just relax some of the conditions a little bit? As your friend, I must advise you to "set some standards first and then refine your list!" "Perhaps better."

Just as ignoring the ability of the person you want to date can lead to future relationships, keeping the "loose coupling" of your objects can bring errors to your code. Also, because if you let any old object "go out" with your subroutine, you may not know the problem until your application executes at run time. In our date-dating analogy, catching bugs at run time is much like having a painful and embarrassing discussion with your date in a trendy Italian restaurant. Yes, you have found the problem, but if you have planned it beforehand, your results will not be "a group of diners staring at you, and you are covered in Italian meatloaf." If you simply apply some tighter criteria to your code, you will be able to catch errors before your application starts running (at compile time). For example, consider the following sample code:

String FirstName = Myrow. ("FirstName"). ToString ();
The above DataRow is untyped; As a result, you must access the value in a string form as the name of the column you want to query (or use the index value of the column in the column collection). It is possible that this column really exists. The data type of a DataRow column is an object; we assume that the basic data type of the FirstName column is a string, but we have to explicitly convert it to a string to use it. If the column name changes (for example, you change it to Personfirstname), then the compiler cannot notify you. Don't do this! So if your code looks more like the following form, your life will be easier and your code will be more reliable:

string FirstName = Personrow.firstname;


In the second example, we have a strongly typed row, and we know that the FirstName property is a string type. Here, there is no messy column name, and there is no messy object conversion problem. The compiler does type checking for us, and we can go on with other tasks without worrying about whether we've entered the column names correctly.

This is also true for all other columns; In short, you should never use a generic object when you can use a more specific type. But wait a minute, please. Where does the strongly typed object originate? I think I can tell you that these objects are created automatically for you. However, just as it takes time and effort to build a good relationship, it takes other efforts to strongly type your object. The good thing about it is that the extra time spent here is worth it, and it saves you more time to spend on debugging in the future.

There are several ways to implement a strongly typed method, and in the remainder of this article we will discuss how to create a strongly typed dataset in Visual Studio 2005, and, of course, analyze the pros and cons of doing so.

  Iii. creating a strongly typed dataset in VS 2005

In fact, a strongly typed DataSet is a generic dataset that defines their own columns and tables in advance, so that the compiler already knows what they will contain. Instead of wrapping your data as a "finger glove", a strongly typed dataset is like a "glove". Each subsequent version of Visual Studio makes the process of strongly typing a dataset easier. In this example, we will use the AdventureWorks database from SQL Server 2005. This simply performs the following steps:

1. Open visual Studio, and then create a new ASP.net web site.

2. In Solution Explorer, take a hit to add a new item and select the dataset and name it adventureworks.xsd. Visual Studio recommends putting this dataset file under the App_Code folder.

3. This adventureworks.xsd is opened in design mode and the TableAdapter Configuration Wizard is activated. Now, just click "Cancel".

4. Navigate to the Server Explorer Toolbox and navigate to your SQL Server 2005 database and AdventureWorks database. (If you have not yet installed the AdventureWorks database, you can download it from Microsoft's SQL Server sample and Sample databases download page, as well as another example of SQL Server 2005.) )

5. Drag the SalesOrderHeader and SalesOrderDetail tables to your DataSet Designer window. The window should now resemble the screenshot below. Note that for each table we join, Visual Studio creates a strongly typed DataTable (the name is based on the original table) and a TableAdapter. This DataTable defines each column for us. This table adapter is the object we use to populate this table. By default, we have a fill () method that finds each row in the table.

This strongly typed dataset returns all of the records in both tables. Since the AdventureWorks database contains a lot of order information, why don't we create a more specific query? We can add methods to our TableAdapter object to retrieve a subset of the records for a more specific table. First, right click on Salesorderheadertableadapter and select "add| Query ". Select Use SQL statements and click the Next button. Then select "Select which returns rows" and click on the Next button. Finally, enter the following query in the window (or use Query Builder to accomplish the same task):

SELECT
SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate,
Status, Onlineorderflag, SalesOrderNumber, Purchaseordernumber,
AccountNumber, CustomerID, ContactID, SalesPersonID, TerritoryID,
Billtoaddressid, Shiptoaddressid, Shipmethodid, Creditcardid,
Creditcardapprovalcode, Currencyrateid, SubTotal, Taxamt, Freight,
TotalDue, Comment, rowguid, ModifiedDate
From Sales.SalesOrderHeader
WHERE (OrderDate > @OrderDate)

This SQL query is a simple select query that has a @orderdate parameter to further narrow the result range. This prevents us from returning every order to the database. Click "Fill a DataTable" and "Return a DataTable" check box, then hit finish. After adding this SELECT statement, your designer should now have an external query that has been added to this salesorderheadertableadapter, please refer to the screenshot below.

  Iv. using a strongly typed dataset on a asp.net page

By creating a strongly typed DataSet, we can easily display this data on a asp.net page by writing only a few lines of code. First, create a asp.net page on your site and watch it in design mode. Then, drag and drop a GridView control onto it, keeping its ID GridView1. Open the source code for the ASP.net page and import the Adventureworkstableadapters namespace at the top of the file (in C #, the syntax is: "Using Adventureworkstableadapters;" )。 Finally, add the following code to the Page_Load event handler:

Create Salesorderheadertableadapter
Salesorderheadertableadapter Salesadapter =
New Salesorderheadertableadapter ();
Get orders that occurred after July 1, 2004
Adventureworks.salesorderheaderdatatable Orders =
Salesadapter.getdataby (New DateTime (2004, 7, 1));
Bind the order results to the GridView
This. Gridview1.datasource = Orders;
This. Gridview1.databind ();

This piece of code is very simple. We create an instance of Salesorderheadertableadapter-we will use it to populate the DataTable. Note that instead of declaring a generic DataTable, we declare an object of the salesorderheaderdatatable type. To populate this DataTable, we call the Getdateby () method and pass it to a DateTime object. Also note that even this retrieval command is strongly typed, because we have to pass a DateTime object, not just a generic object. The following screenshot shows a clear result of the example code above.

In addition to binding the results to the GridView by code, you can also use a ObjectDataSource, Set its TypeName property to Adventureworkstableadapters.salesorderheadertableadapter, and set its selectmethod to GetData or Getdataby.

Five, inserting, updating, and deleting data with a strongly typed dataset

In this article, we have seen how to select data from a database using a strongly typed DataSet. However, you can also use these tools to insert, UPDATE, and delete basic database data.

In addition to the need to write code to access the database, another great advantage of using this strongly typed DataSet is that there is no compiler cannot check the string column name lurking in our code and we don't have to do any object conversions. If we have ever changed our database schema, once we have updated our adventureworks.xsd files, we will notice all the great changes that exist in our applications during compilation.

Six, summary

In fact, in addition to using strongly typed datasets, there are other ways to implement the strong typing of your application. You can create custom classes that are lighter than datasets and can respond correctly to your database. Also, there are third-party software developers who provide tools to automate this process. One of the special products is Llblgen Pro, one of my favorite tools, and I wrote a book about it: Rapid C # Windows development:visual Studio, SQL Server 2005,and l Lblgen Pro ". Another popular tool is Codesmith. Even Microsoft is using a similar tool-dlinq, which is still in beta and will not be listed for the next year at least.

If you use the Visual Studio strongly typed DataSet method, you do not need to purchase any additional software-this is an obvious advantage. All of these solutions have different characteristics and advantages, but the main benefits of strongly typing your relational data are reliability, fewer bugs, and less debugging time, and it's also easier to analyze the impact of database schema changes and implement them. Finally, hopefully you've learned about the advantages of strong typing. I wish you luck!



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.