您的位置: 主页 > 编程开发 > ASP.NET > ado.net快速上手实践篇(二)ADO.NET

ado.net快速上手实践篇(二)ADO.NET
时间:11-07-08 来源:网络 作者:admin 阅览:

  五、dal层数据访问实现

  在这里我们使用前一篇文章里实现的数据持久化层和伪SqlMapper对象,实现数据操作。下面我们来看看Dal下核心的Dao如何实现:

  还记得我们在IBatis.net下面的dao类是怎么实现的吗?没错,我们根据一个基类BaseDAO和它的构造函数,实现dao的配置加载。但是楼猪的实现没有那么复杂和强大,本文的实现其实就是通过BaseDAO和构造函数获取数据库连接对象的key,初始化一个SqlMapper,然后利用SqlMapper对象进行基本的CRUD等等数据操作。那么我们如何利用BaseDAO和构造函数就像以前在IBatis.net系列文章里的提到的Dal层下那样进行SqlMapper的初始化呢?

  1、在AdoNetDataaccess.Mapper下我们定义公共的BaseDAO类

  代码

  namespace AdoNetDataAccess.Mapper

  {

  public abstract class BaseDAO

  {

  #region PRoperties

  public SqlMapper SqlMapper { get; set; }

  #endregion

  #region Constructor

  private BaseDAO()

  {

  }

  /// <summary>

  /// SqlMapper属性适用

  /// </summary>

  /// <param name="mapperName"></param>

  public BaseDAO(string mapperName)

  {

  this.SqlMapper = MapperUtill.GetMapper(mapperName);

  }

  #endregion

  }

  }

  2、初始化SqlMapper的实用类

  代码

  using System;

  using System.Collections.Generic;

  using System.Configuration;

  namespace AdoNetDataAccess.Mapper

  {

  using AdoNetDataAccess.Core.Contract;

  using AdoNetDataAccess.Core.Implement;

  public sealed class MapperUtill

  {

  #region fields

  public static string currentSqlKey = "sqlConn";

  public static int cmdTimeOut = 15;

  private static readonly object objSync = new object();

  private static readonly IDictionary<string, SqlMapper> dictMappers = new Dictionary<string, SqlMapper>();

  #endregion

  #region constructor and methods

  private MapperUtill()

  {

  }

  static MapperUtill()

  {

  try

  {

  cmdTimeOut = int.Parse(ConfigurationManager.AppSettings["db_timeOut"]);

  }

  catch

  {

  cmdTimeOut = 15;

  }

  //实例化SqlDbMapper

  for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)

  {

  string key = ConfigurationManager.ConnectionStrings[i].Name;

  string value = ConfigurationManager.ConnectionStrings[i].ConnectionString;

  CreateMapper(key, value, cmdTimeOut);

  }

  }

  public static SqlMapper GetSqlMapper(string key)

  {

  return MapperUtill.GetMapper(key);

  }

  public static SqlMapper GetCurrentSqlMapper()

  {

  return MapperUtill.GetMapper(currentSqlKey);

  }

  public static void CreateMapper(string connKey, string sqlConStr, int connTimeOut)


ASP.NET相关
关于<< ado.net快速上手实践篇(二)ADO.NET >>的评论 查看所有评论