在15分钟内构造一个数据访问层。

来源:互联网 发布:赛默飞变色龙软件 编辑:程序博客网 时间:2024/05/01 10:05

本文源于对官方教程的翻译,原文请查看官方网站。

Build a Data Access Layer in less than 15 minutes
15分钟内构造一个数据访问层。

DOWN LINKS
下载链接

·  Download a free 30 day trial of CodeSmith Professional (下载一个免费的30天的试用版CodeSmith)

·  Download latest .netTiers templates (下载最新的.net(Tiers不知道该如何翻译)模版)

·  Watch a video presentation of this article(观看本教程的视频版)

Introduction
简介

In this article you will learn how to build a Data Access Layer using Microsoft’s Enterprise Library in less than 15 minutes using CodeSmith and the .netTiers Template Library.
在这篇文章中,你将会学习到如何使用微软的企业库在15分钟之内借助CodeSmith.netTiers模版库构造一个数据访问层。

The Data Access Layer, from here on out referred to as the DAL, is the layer of application functionality that encapsulates all interactions with the database. Typically this type of code is hand written and requires specialized knowledge, not only of .NET, but of the specific data access routines too. Writing the DAL code for an application is one of the most monotonous, time consuming, repetitive, and likely bug-ridden aspects of building software.
数据访问层,这里我们简写为DAL,是应用程序中与数据库交互的封装。这些代码手写的时候需要一些专业的知识,仅仅.net是不够的,还需要一些数据访问的知识。对应用程序写DAL代码是枯燥,耗时,重复性高,而且也是BUG的高发地段。

For this article we’ll use the sample Northwind database in SQL Server, but these examples will work with any database. And of course, after this article you’ll no longer view writing the DAL for your application as monotonous and time consuming, but quick, easy, and simple!
在这个文档中,我们将会使用SQL Server 中的实力数据库Northwind,但是这个例子可以工作与所有的数据库。当然,在学习了这个教程后你也不必再为你的应用程序机械,重复,枯燥的编写DAL,它将会变得轻松简单。

If you follow this article at the end you will be able to create a complete best practices Data Access Layer in just under 1 minute (the other 14 minutes are for downloading the software the first time).
在这个文章结束时你将能够在一分钟之内构造一个不错的DAL(其余的14分钟时用于第一次使用时下载软件)

 

Code Generation, a brief overview
简单介绍一下代码生成

Code generation, or the use of software tools to generate code, is not a new concept. In fact, code generation has been around for quite some time. In this article I’m going to use CodeSmith as the tool for generating both the code and T-SQL scripts for the DAL.
代码生成,或者使用软件工具来生成代码并不是一个新的玩意儿。事实上这个东西很久之前就有了。在这个文章中,我将使用CodeSmith作为代码和T-SQL脚本的代码生成工具。

CodeSmith is a developer productivity tool that enables developers to use templates to control the formatting and desired code output. Therein is the beauty of CodeSmith - software developers still retain full control over the code created through templates. Templates provide the opportunity for people to create new and interesting code reuse and generation libraries, such as the .netTiers templates used in this article.
CodeSmith
是一个允许开发者使用模版来控制生成代码的格式和生成的代码的输出的开发工具。开发者通过模版仍然保持对生成的代码的完全掌控----在这一点上CodeSmith做的很漂亮。模版提供人们一种对创建新代码和重用代码生成库的机会。例如本文中使用的.netTier模版。

Step 1 – Setup
第一步----安装

The first step is to get the necessary tools (CodeSmith) and templates (.netTiers). CodeSmith is a commercial developer tool, but there is a 30-day free trial we can use for the purpose of this article:
首先我们需要得到必须的工具(CodeSmith)和模版(.netTiers)CodeSmith是一个商业开发工具,但是我们也可以得到一个30天的免费试用版本(对于我们的教程这就足够了)。

Download and Install CodeSmith
下载和安装CodeSmith

http://www.codesmithtools.com/

CodeSmith comes with a lot of built-in templates and the next service pack will include the .netTiers templates shown in this article.
CodeSmith
有一大堆的内建模版和next服务包,包括我们在本文中要使用的.netTiers

Now that CodeSmith is installed, download the .netTiers template library:
现在CodeSmith已经被安装上,下载.netTiers模版库。

Download .netTiers Template Library for CodeSmith
下载CodeSmith.netTiers模版库

http://www.nettiers.com/

On the .netTiers site click on the "Latest Download" link in the left-column; next, click on "available for download" at the top of the page. This will take you to another page where you can download the latest Windows MSI installer.
.netTiers页面上单击左边一列的“Latest Download”链接,单击页面顶端的“available for download.这将会链接到下载页面。

The last step is to ensure you have a SQL Server database setup and have a connection string you can use to connect to the database.
下一步是确信你的机子上安装了SQL Server数据库,并且你能够拥有一个链接到数据库的链接字符串。

Step 2 – CodeSmith
第二步—CodeSmith

After downloading and installing CodeSmith you should be able to open it from All Programs | CodeSmith 3.1 | CodeSmith Studio. Before we use the .netTiers templates you need to familiarize yourself with CodeSmith.
在下载和安装了CodeSmith后,你将能够在开始菜单的 所有程序|CodeSmith|CodeSmith Studio下面打开它。在我们使用.netTiers模版的时候你需要先熟悉一下CodeSmith的开发环境。

As mentioned in the introduction, CodeSmith is a template driven code generation tool. There is a window on the right of CodeSmith called the Template Explorer. The Template Explorer provides you with a quick and easy way of accessing the templates you’ve installed or written:
正如上面所提到的,CodeSmith是一个模版驱动的代码生成工具。在CodeSmith右边有一个称作模版管理器的窗口。模版管理器提供了一个方便简捷的方法来访问你安装的或者曾经写过的模版。

To explain the rest of CodeSmith we need a template. Open the Hashtable.cst template from Template Explorer by double-clicking on it.
要了解CodeSmith的剩余部分,我们需要一个模版。从模版管理器中双击打开Hashtable.cst模版。

Hashtable.cst is one of the great sample templates included with CodeSmith and is used to generate strongly typed collections that use the .NET Hashtable type as the base data type. Before we explain the template, let’s quickly look at another window in CodeSmith, the Properties window:
Hashtable.cst
CodeSmith中一个很不错的模版。它能够借助.NET Hashtable类作为父类产生强类型的结合。在解释模板之前,让我们浏览一下CodeSmith中的另一个窗口----属性窗口。

The Properties window allows you to set properties for the template. When using the Hashtable.cst template we need to set some common elements such as the generated ClassName, ItemType, and KeyType. For example, if you wanted to create a strongly typed collection of Person objects accessed by an integer with a class name of PersonCollection, you would set the ClassName to PersonCollection, the ItemType to Person, and the KeyType to int. You could generate the source for this strongly typed collection now by simply clicking the Run button in CodeSmith (found on the toolbar).
属性窗口允许你设置模板的属性。当使用Hashtable.cst模版之前,我们需要设置一些元素,例如生成的类名。值名和键名。例如,如果你想创建通过一个整数访问的Persong类的强类型集合PersonCollection,你需要设置ClassName属性的值为PersonCollectionItemType属性的值为PersonKeyType属性的值为int。你现在可以通过单击CodeSmith中工具栏上的Run按钮来产生这个强类型集合的源码。

If you took a moment to examine the Hashtable.cst template file you might say to yourself, "This looks a lot like ASP.NET". You’d be correct. CodeSmith templates are modeled after ASP.NET Pages and share many similar ideas. However, whereas ASP.NET Pages are used to generate HTML, CodeSmith Templates are used to generate source files or other text files.
如果你花费时间来查看一下Hashtable.cst模版文件,你或许会惊叹:“哇,这跟ASP.NET的代码太像了!”,是的,CodeSmith模板的语法的确根ASP.NET有异曲同工之妙。然而,ASP.NET是被用来生成HTML的,CodeSmith模版是用来生成原代码文件或者其他的文本文件的。

The most important thing to remember about CodeSmith is that CodeSmith does not limit your creativity by forcing you into what code is generated. Since it is template driven the code output is completely controlled by you.
你需要了解关于CodeSmith的重要的一点是它并不限制您的创造力来强迫你使用某种格式的生成的代码(没有任何的副作用)。一次它是模版驱动的代码并且输出是可以被你完全控制的。

Step 3 – Generate the DAL
第三步----产生DAL代码

Now that you have a basic understanding of CodeSmith I want to show you the .netTiers templates.
你已经对CodeSmith有一个基本的了解了,现在我想介绍一下.netTiers模版。

Remember, the idea behind CodeSmith is that it allows you to write code faster, with fewer defects. The .netTiers templates take that one step further and create a DAL for you that follows all the recommended Patterns & Practices from the team at Microsoft by the same name.
记住,CodeSmith的意图是让你更快更少错误的编写代码。.netTiers模版提供了使用常用的方法创建DAL的代码。(这些翻译的不好,请查看原文)

First we need to add the .netTiers templates to the CodeSmith Template Explorer:
首先,我们需要添加.netTiers模版到CodeSmith模版管理器:

  1. In Template Explorer click on the Open Folder icon to browse for a folder containing templates.
    在模版管理器中单击打开文件夹图标,来浏览一个文件加内所包含的模板。
  2. Go to the folder where .netTiers was installed. On my computer this is:
    C:/Program Files/SerialCoder/NetTiers 0.9.2 - Caribert/Templates/
    打开.netTiers被安装的文件夹的位置,在我的电脑上是:
    C:/Program Files/SerialCoder/NetTiers 0.9.2 - Caribert/Templates/
  3. Once this folder is created as a shortcut in Template Explorer, expand it and select NetTiers.cst
    一旦这个文件夹被创建作为模版管理器中的快捷方式,展开并选择NetTiers.cst
  4. Now that the .netTiers templates are installed you need to configure a data source. With the NetTiers.cst template open, open the Properties window and configure a Source Database by clicking on the ellipses:

    现在已经安装了.netTiers模版,你需要配置一下数据源。打开NetTiers.cst模版,打开属性窗口通过点击下面的按钮来配置数据源。
  5. This opens the Database Picker, we’re going to create a new data source so click on the ellipses in the Database Picker to open the Data Source Manager. In the screen shot below is an example of how this should look (choose a name that let’s you quickly know what database you’re working with):

    这将会打开数据库选择器,我们将创建一个新的数据源,因此点击数据库选择器来打开数据源管理器。如下面的窗口所示。(选择一个你能够容易记住的名字)
  6. Test the connection to ensure it works and then back out of these dialog windows by clicking OK. Make sure the new data source is selected.
    测试一下链接。确信它能够连接到数据库,然后确定返回。
  7. Finally, set the EntireDatabase property to True, set the NameSpace property to Demo, and set the OutputDirectory property to the directory where you would like the generated files to be located. You will need to create the output directory if it doesn’t exist.
    最后,设置EntireDatavase属性为True,设置命名空间为Demo,设置OutputDirectory属性作为你想生成的代码文件的目录。如果目录不存在,你需要创建一个。

Once you’ve completed these steps your property window for the NetTiers.cst template should look similar to the screenshot below (changes highlighted):
一旦尼完成了这些操作,你的NetTiers.cst的属性窗口将会如下图所示。

We are not going to show anywhere near the full capabilities of .netTiers in this article or CodeSmith, but we’ve now done enough to generate a DAL. Click the Run button in the CodeSmith toolbar to generate the code.
我们不会讲解.netTier的内容。但是我们现在掌握的东西已经足够来生成DAL了,点击工具栏中的Run按钮来生成代码。

Step 4 – Review the Generated Code
第四部----预览一下生成的代码

Open Visual Studio .NET and if you followed the directions above you should find a Demo.sln file in the c:/NetTiers/Northwind_Demo/ directory.
打开Visual Studion .NET 如果你按照我们的向导执行,那么你可以在c:/NetTiers/Northwind_Demo/ directory下发现一个Demo.sln文件

Take a moment and browse the solution and project files in Visual Studio:
用一点时间来浏览一下显示在Visual Studio 中的解方案和工程

You should find 3 projects within the solution:
你将会发现在解决方案下有3个项目

Demo – the main library that contains the classes you will use within your application to interact with the database.
Demo ---
你需要在你的应用程序中使用的与数据库交互得主类库项目

Demo.DataAccessLayer – the library containing the data access implementation code.
Demo.DataAccessLayer ----
包括数据访问扩展代码的类库。

Demo.DataAccessLayer.SqlClient – the library containing the Microsoft Patterns & Practices classes for working with the database.
Demo.DataAccessLayer.SqlClient –
包括Microsoft Pattern & Practices 的数据类。

Step 5 – Compile …and we’re done!
第五步 编译我们已经完成了

Next, with Visual Studio still open, compile the project.
然后,保持Visual Studion 处于打开状态,编译项目。

Congratulations! You now have a Data Access Layer that implements the recommended best practices from the Microsoft Patterns & Practices group for working with a database.
祝贺!你现在已经有了一个微软推荐的格式的数据访问层。

You can now begin using your new Data Access Layer in other Visual Studio .NET projects. For example, below is code to retrieve, update and then delete an employee record.
你可以开始在其他的Visual Studio .net项目中使用这个新的数据访问层。例如,下面的代码是获取,更新和删除一个员工记录的示例。

using Demo.DataAccessLayer.SqlClient;

 

// Select by primary key

Employee employee = SqlDataRepository.EmployeeProvider.GetByEmployeeID(13);

employee.FirstName = "John";

employee.LastName = "Doe";

 

// Save changes

SqlDataRepository.EmployeeProvider.Save(employee);

 

// Delete record

SqlDataRepository.EmployeeProvider.Delete(employee);

   

For more information on how to use the generated DAL, take a look at the .netTiers manual here:
想知道更多的关于如何使用生成的DAL代码的信息,请查看.netTiers手册:

http://www.nettiers.com/nettiers-manual-v1.aspx

Remember all of the Data Access Layer code was generated by templates, so later when you change your database structure you can simply rebuild the DAL again from the templates. Furthermore, you can even extend the templates with your own ideas, comments, naming conventions, patterns, and so on.
记住所有的数据访问层的代码都是通过模版声称的,因此,随后当你改变你的数据库的结构的时候,你可以通过刚才的模版简单的重新构造DAL。更牛的是,你甚至可以用你的意图来扩展这些模版,注释,转换,样式等等。

Conclusion
结论

The possibilities for CodeSmith templates are limited only by your own creativity. As I’ve demonstrated in this article, CodeSmith is an exceptionally powerful developer productivity tool. Coupled with the .netTiers templates you can write a best practices Data Access Layer for your application in a matter of minutes.
CodeSmith
模版的能力只受你的创造力的约束。就像我在本文中解释的,CodeDmith是一个超级强大的开发生产工具。在模版的帮助下你可以在短短的几分钟之内构造一个优秀的数据访问层。

You can also watch a video of this presentation here:
本教程视频版到下面的网址观看:

http://community.codesmithtools.com/r.ashx?id=1

One of the fun features added into version 3.1 was a simple "value calculator". The value calculator provides a conservative estimate of the time saved by using CodeSmith:
3.1
版中的一个新特性是简单的“值计算”。值计算提供了一个保守的通过使用CodeSmith 节省的时间的评估。

As shown in the screenshot above, using the .netTiers templates with CodeSmith generated 91,559 lines of code. Assuming a developer can write approximately 50 lines of code per-hour (had we written this manually) writing the code we generated would have taken 1,800 hours. Taking this a step further and assuming that a developer’s time is approximately $60/hour, CodeSmith and .netTiers together saved you 1,800 hours of your life and $109,000 for your company!

So get CodeSmith… and then go ask for a raise.
就像上面的在抓屏图片中显示的那样,.netTiers模版生成了91559行代码,假设一个开发者每小时能够写50行代码(手工状态下)。那么我们写这些代码将会花费1800小时。进一步推算,如果开发人员的薪水是每小时60美元,那么CodeSmith使用.netTiers将会节省你1800小时的生命并为您的公司节省109000美元。(哎,咱怎么连份工作都找不到呢?,老外杂就这么强呢?)

 

原创粉丝点击