[导读]实现数据访问功能是大多数使用.net framework的开发人员的核心工作,并且由他们生成的数据访问层是其应用程序必不可少的组成部分。本文概述了五个建议,希望您在使用visual studio .net和.net framework生成数据访问层时予以考虑。 这些技巧包括通过使用基类来利用面向对象的技术和.net framework基础结构,通过遵循某些准则使类变得易于继承,以及在就表示方法和外部接口进行决策之前仔细分析自己的需要。
如果您要针对microsoft .net framework来开发以数据为中心的应用程序,那么您终将需要创建数据访问层(dal)。您可能知道在.net framework中生成代码带来的一些好处。因为它同时支持实现和接口继承,所以您的代码可以具有更高的可重用性,尤其是可供您的组织中那些使用与framework兼容的其他编程语言的开发人员重用。在本文中,我将介绍为了针对基于.net framework的应用程序而开发dal的五个规则。在开始之前,我要说明的是,基于本文中讨论的规则生成的任何dal都将与windows平台上的开发人员所喜爱的传统的多层或n层应用程序兼容。在该体系结构中,表示层由对协调数据访问层工作的业务层进行调用的web窗体、windows窗体或xml web service代码组成。该层包含多个数据访问类。另外,在不需要进行业务处理协调的情况下,表示层可能会直接对dal进行调用。该体系结构是传统的模型-视图-控制器(mvc)模式的变体,并且在许多方面由visual studio.net及其公开的控件所采用。
规则1:使用面向对象的功能
最基础的面向对象的任务是使用继承的实现来创建抽象基类,该基类可以包含所有数据访问类可以通过继承使用的服务。如果这些服务足够通用,则可以通过在整个组织中分发基类来对它们进行重用。例如,在最简单的情况下,基类可以为派生类完成连接对象的创建,如图1所示。
| imports system.data.sqlclient namespace acme.data public mustinherit class dalbase : implements idisposable private _connection as sqlconnection protected sub new(byval connect as string) _connection = new sqlconnection(connect) end sub protected readonly property connection() as sqlconnection get return _connection end get end property public sub dispose() implements idisposable.dispose _connection.dispose() end sub end class end namespace |
| public class webdata : inherits dalbase public sub new() mybase.new(configurationsettings.appsettings("connectstring")) end sub public function getorders() as dataset dim da as new sqldataadapter("usp_getorders", me.connection) da.selectcommand.commandtype = commandtype.storedprocedure dim ds as new dataset() da.fill(ds) return ds end function end class |
| <constructionenabled(true), _ transaction(transactionoption.supported), _ eventtrackingenabled(true)> _ public mustinherit class dalservicedbase : inherits servicedcomponent private _connection as sqlconnection protected overrides sub construct(byval s as string) _connection = new sqlconnection(s) end sub protected readonly property connection() as sqlconnection get return _connection end get end property end class |
| public overloads function getorders() as dataset public overloads function getorders(byval customerid as integer) as dataset |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器