开发自己的Data Access Application Block[上篇]
经常在网上看到对ORM的讨论沸沸扬扬,我也来凑个热闹,谈谈我写的一个ORM。最近在做一项工作,把我们经常用到的一些业务逻辑抽象出来,写成一个个的Application Block,使之可以运用到不同的Application中,比如Data Access,Messaging,Auditing,Data bind
经常在网上看到对ORM的讨论沸沸扬扬,我也来凑个热闹,谈谈我写的一个ORM。最近在做一项工作,把我们经常用到的一些业务逻辑抽象出来,写成一个个的Application Block,使之可以运用到不同的Application中,比如Data Access,Messaging,Auditing,Data binding等等。现在先做一个Data access application block。由于时间仓促,没有进行什么优化和较多的测试,大家不必深究我所提供的Code ,我只希望为大家的ORM提供另一种想法。这个application block应达到的目的:
-
封装所有的Data Access操作。
-
适合主流的DBMS:SQL Server(2000和2005),Oracle(9i和10g),DB2。
-
尽量简化Developer的操作和提供最大的灵活性,在Data Retrieval方面,只要指定SQL或者Stored Procedure和相应的参数;在Data Update方面,既可以直接调用SQL和Stored Procedure,还可以把包含多个相互关联Data Table的Dataset通过一次调用实现数据的更新。此外,可以自由地选择使用SQL还是Stored procedure;可以使用Commander builder生成Command或者使用基于Mapped stored procedure生成的Command进行数据更新。
-
实现泛型编程,使使用该AppBlock的代码能够适合所有的数据库。
-
实现Transaction。
-
提供可配置性,包括不同数据库的配置,不同Data Mapping的配置等等。
下面是该AppBlock使用到的Entity:
-
Database:Abstract Class,封装了绝大部分和具体数据库无关的Data Access操作逻辑。通过两个Mapping:IDbParameterNameMapping和IStoredProcedureNameMapping,实现Dataset和Db的一个映射。比如Dataset中Data table name和Stored procedure name的Mapping,Data table中Field和Stored procedure中参数名的Mapping。这两个Mapping是可以配置的,你只需要实现提供的Interface编写适合你的Mapping provider就可以了。
-
SqlDatabase:封装基于SQL Server 的操作。ADO.NET 2.0在1.0的基础上作了很大的改善,主要的增加的大量的基类,为我们进行泛型编程,编写和具体Db无关的代码变得异常容易。所以我们把大多数Data Access的操作可以封装在Abstract Database类中,SqlDatabase中的内容实际上是很少的。
-
OracleDatabase:封装基于Oracle的操作。
-
IDbParameterNameMapping和IStoredProcedureNameMapping:我想大家都是这样的感受,实现ORM的本质就是实现内存中的数据(主要是Dataset)和数据库的一个映射。在Dataset和数据库中的Table相互Mapping方面,我觉得没有必要采用特殊的Mapping,直接和简单易行的就是Table和Dataset中的Data Table完全匹配(table name 和field name完全匹配)。所以重要的是实现Dataset和Stored procedure的Mapping:Table Name如何与进行Insert,Update,Delete的Stored procedure name匹配,不同Version(original & current)的Field如何与Stored procedure的Parameter name 匹配。而这样一个匹配应该是可配置的,因为每个Application在数据库设计时的命名都有各自的要求,所以我在这里采用的Provider的设计模式。用户可以实现这两个Interface编写适合自己的Mapping provider,通过我提供的Configuration block很容易地完成配置。同时,我写了一个默认的,简单的Mapping:SimpleDbParameterNameMapping和SimpleStoredProcedureNameMapping。
有一点需要补充的是,要实现上面的Mapping,对Stored Procedure的命名有较高的要求,手工编写的方式已经不能适合我们的要求,所以我们需要一个生成Stored procedure的Generator,这个Generator也使用这两个可配置的Mapping接口。
-
DatabaseFactory: 一个静态的类,根据配置的信息创建你需要的具体的Database对象,实现泛型化编程。
-
DataAccessConfigurationCollection,DataAccessConfigurationElement,DataAccessConfigurationdiv 三个Configuration的Class。
为了使大家清楚地看出这个Application block所有的操作,我把所有的操作封装在一个IDatabase的interface中,不过需要注意的是,我采用的是基于Abstract class的编程,而不是基于Interface的编程,相信大家对这两种方式讨论得已经碰倒的太多了,孰优孰劣我就不想对说了。这个IDatabase 接口,只是展示所有Operation之用,并没有在我的代码中用到。
namespace Artech.ApplicationBlock.DataAccess
{
public interface IDatabase
{
Fill a System.Data.DataSet with retrieved data.#region Fill a System.Data.DataSet with retrieved data.
void FillDataSet(DataSet dataInfo, string commandText, IDictionarystring, object> parameters);
void FillDataSet(DataSet dataInfo, string tableName, string commandText, IDictionarystring, object> parameters);
void FillDataSet(DataSet dataInfo, string tableName, CommandType commandType, string commandText, IDictionarystring, object> parameters);
#endregion
Save the changed data which is stored in a dataset into database.#region Save the changed data which is stored in a dataset into database.
void UpdateData(DataSet dataInfo);
void UpdateData(DataTable table);
void UpdateData(DataTable table, string insertCommandText, string updateCommandText, string deleteCommandText,
Dictionarystring, object> insertParameters, Dictionarystring, object> updateParameters, Dictionarystring, object> deleteParameters);
void UpdateData(DataTable table, CommandType commandType, string insertCommandText, string updateCommandText, string deleteCommandText,
Dictionarystring, object> insertParameters, Dictionarystring, object> updateParameters, Dictionarystring, object> deleteParameters);
void UpdateData(DataTable table, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand);
#endregion
Execute a command and return the affect row count.#region Execute a command and return the affect row count.
int ExecuteNonQuery(CommandType commandType, string commandText, Dictionarystring, object> inputParameters, Dictionarystring, object> outputParameters);
int ExecuteNonQuery(CommandType commandType, string commandText, Dictionarystring, object> inputParameters);
int ExecuteNonQuery( string commandText, Dictionarystring, object> inputParameters, Dictionarystring, object> outputParameters);
int ExecuteNonQuery( string commandText, Dictionarystring, object> inputParameters);
#endregion
Execute a command and return the data in the form of data reader.#region Execute a command and return the data in the form of data reader.
DbDataReader ExecuteReader(CommandType commandType, string commandText, Dictionarystring, object> inputParameters, Dictionarystring, object> outputParameters);
DbDataReader ExecuteReader(CommandType commandType, string commandText, Dictionarystring, object> inputParameters);
DbDataReader ExecuteReader(string commandText, Dictionarystring, object> inputParameters, Dictionarystring, object> outputParameters);
DbDataReader ExecuteReader(string commandText, Dictionarystring, object> inputParameters);
#endregion
Execute a command and return a scalar value.#region Execute a command and return a scalar value.
object ExecuteScalar(CommandType commandType, string commandText, Dictionarystring, object> inputParameters, Dictionarystring, object> outputParameters);
object ExecuteScalar(CommandType commandType, string commandText, Dictionarystring, object> inputParameters);
object ExecuteScalar(string commandText, Dictionarystring, object> inputParameters, Dictionarystring, object> outputParameters);
object ExecuteScalar(string commandText, Dictionarystring, object> inputParameters);
#endregion
Transaction based operation#region Transaction based operation
void BeginTransaction();
void Commit();
void RollBack();
#endregion
}
}
这个列表和大部分ORM没有什么太大的区别,大家已经司空见惯,实现起来也不会有什么太大的困难。对于大部分操作,我不会做详细的介绍。接下来我们来简要地看看这样一个AppBlock是如何实现的。
1. Data Mapping
我们首先来看看Data Mapping:实现Dataset中Table name和Stored Procedure Name的Mapping,以及Dataset 中的Field 和Stored procedure的参Parameter name的Mapping。
IDbParameterNameMapping
using System;
using System.Collections.Generic;
using System.Text;
namespace Artech.ApplicationBlock.DataMapping
{
/**////
/// IStoredProcedureNameMapping defines the mapping between the data table name and the name of stored procedures to perform insertion, modification and deletion operation.
///
public interface IStoredProcedureNameMapping
{
/**////
/// Get the name of stored procedure to perform seletion operation.
///
/// The name of the database table.
///
string GetSelectStoredProcedureName(string tableName);
/**////
/// Get the name of stored procedure to perform insert operation.
///
/// The name of the database table.
///
string GetInsertStoredProcedureName(string tableName);
/**////
/// Get the name of stored procedure to perform modification operation.
///
/// The name of the database table.
///
string GetModifyStoredProcedureName(string tableName);
/**////
/// Get the name of stored procedure to perform deletion operation.
///
/// The name of the database table.
///
string GetDeleteStoredProcedureName(string tableName);
}
}
IDbParameterNameMapping
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace Artech.ApplicationBlock.DataMapping
{
/**////
/// IDbParameterNameMapping define the defult mapping between the source column name and the parameter name of the corresponding stored procedure.
///
public interface IDbParameterNameMapping
{
/**////
/// Get the source column name based on the parameter name of the related stored procedure.
///
/// The parameter name of the corresponding stored procedure.
///
string GetSourceCoulmnName(string patameterName);
/**////
/// Get the source parameter name based on the source column name.
///
/// The source column name corresponding to the parameter name.
/// The data row version of the source solumn conressponding to the parameter.
///
string GetParameterName(string columnName, DataRowVersion rowVersion);
}
}
这两个Mapping主要用在通过Dataset跟新数据库的场景,利用IDbParameterNameMapping,我们通过Dataset中各个Table name获得对它进行Insert,Update,Delete操作的Stored procedure的name。利用IDbParameterNameMapping,我们可以为Stored procedure的Parameter指定对应的Source field.
注:GetParameterName方法实际上是不需要的,我把使用在另一个AppBlock中。
接下来我们来写两个实现了上面连个Interface的默认的mapping:SimpleStoredProcedureNameMapping和SimpleDbParameterNameMapping。他实际上实现了这样的Mapping:比如Table name为T_ABC_DEF(我经常用的命名方式:以T开头代表Table,名称大写并一下划线连接),那么对应的Stored procedure name分别为:sp_abc_def_s(Select), sp_abc_def_i(Insert), sp_abc_def_u(Update), sp_abc_def_d(delete)。如果Field name为ABC_123,那么对于Original version的Parameter name为o_abc_123(o代表Original),Current version的Parameter name为p_abc_123(p代表一般意义的Parameter)。
using System;
using System.Collections.Generic;
using System.Text;
namespace Artech.ApplicationBlock.DataMapping
{
/**////
/// IStoredProcedureNameMapping defines the mapping between the data table name and the name of stored procedures to perform insertion, modification and deletion operation.
///
public class SimpleStoredProcedureNameMapping:IStoredProcedureNameMapping
{

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











멀티 스레딩의 장점은 특히 많은 양의 데이터를 처리하거나 시간이 많이 걸리는 작업을 수행하기 위해 성능 및 리소스 활용도를 향상시킬 수 있다는 것입니다. 이를 통해 여러 작업을 동시에 수행하여 효율성을 향상시킬 수 있습니다. 그러나 너무 많은 스레드가 성능 저하로 이어질 수 있으므로 CPU 코어 수와 작업 특성에 따라 스레드 수를 신중하게 선택해야합니다. 또한 다중 스레드 프로그래밍에는 교착 상태 및 레이스 조건과 같은 과제가 포함되며 동기화 메커니즘을 사용하여 해결해야하며 동시 프로그래밍에 대한 확실한 지식, 장단점을 측정하고주의해서 사용해야합니다.

SQL IF 명령문은 구문을 다음과 같이 조건부로 실행하는 데 사용됩니다. if (조건) 그런 다음 {state} else {state} end if;. 조건은 유효한 SQL 표현식 일 수 있으며 조건이 참이면 당시 조항을 실행하십시오. 조건이 false 인 경우 else 절을 실행하십시오. 명세서를 중첩 할 수있는 경우 더 복잡한 조건부 점검이 가능합니다.

Root로 MySQL에 로그인 할 수없는 주된 이유는 권한 문제, 구성 파일 오류, 암호 일관성이 없음, 소켓 파일 문제 또는 방화벽 차단입니다. 솔루션에는 다음이 포함됩니다. 구성 파일의 BAND-ADDRESS 매개 변수가 올바르게 구성되어 있는지 확인하십시오. 루트 사용자 권한이 수정 또는 삭제되어 재설정되었는지 확인하십시오. 케이스 및 특수 문자를 포함하여 비밀번호가 정확한지 확인하십시오. 소켓 파일 권한 설정 및 경로를 확인하십시오. 방화벽이 MySQL 서버에 연결되는지 확인하십시오.

노드 환경에서 403 오류를 반환하는 타사 인터페이스를 피하는 방법. node.js를 사용하여 타사 웹 사이트 인터페이스를 호출 할 때 때때로 403 오류를 반환하는 문제가 발생합니다. � ...

Vue Axios의 크로스 도메인 문제를 해결하는 방법 : Cors 플러그인을 사용하여 Websocket을 사용하여 JSONP를 사용하여 Axios 프록시를 사용하여 서버 측의 CORS 헤더 구성

Apache에서 Zend를 구성하는 방법은 무엇입니까? Apache 웹 서버에서 Zend 프레임 워크를 구성하는 단계는 다음과 같습니다. Zend 프레임 워크를 설치하고 웹 서버 디렉토리로 추출하십시오. .htaccess 파일을 만듭니다. Zend 응용 프로그램 디렉토리를 작성하고 Index.php 파일을 추가하십시오. Zend 응용 프로그램 (application.ini)을 구성하십시오. Apache 웹 서버를 다시 시작하십시오.

EasyWechat5.5에서 구성 요소를 얻으십시오 ...

이 기사는 데비안 시스템에서 Apache Logs를 분석하여 웹 사이트 성능을 향상시키는 방법을 설명합니다. 1. 로그 분석 기본 사항 Apache Log는 IP 주소, 타임 스탬프, 요청 URL, HTTP 메소드 및 응답 코드를 포함한 모든 HTTP 요청의 자세한 정보를 기록합니다. 데비안 시스템 에서이 로그는 일반적으로 /var/log/apache2/access.log 및 /var/log/apache2/error.log 디렉토리에 있습니다. 로그 구조를 이해하는 것은 효과적인 분석의 첫 번째 단계입니다. 2. 로그 분석 도구 다양한 도구를 사용하여 Apache 로그를 분석 할 수 있습니다.
