为PetaPoco添加Fill方法

  因为公司框架中的很多地方用到DataTable,直接将DataTable作为数据源绑定到DataGridView,所以为PetaPoco添加了两个方法,一个是用以填充单个DataTable,一个是用以多结果集时填充DataSet。

        #region operation Fill

        /// <summary>
        /// 填充一个DataSet
        /// </summary>
        /// <param name="ds">引用的DataSet</param>
        /// <param name="sql">sql语句</param>
        /// <param name="args">参数</param>
        public void Fill(DataSet ds, string sql, params object[] args)
        {
            OpenSharedConnection();

            try
            {
                using (var cmd = CreateCommand(_sharedConnection, sql, args))
                {
                    using (DbDataAdapter dbDataAdapter = _factory.CreateDataAdapter())
                    {
                        dbDataAdapter.SelectCommand = (DbCommand)cmd;
                        dbDataAdapter.Fill(ds);
                    }
                }
            }
            finally
            {
                CloseSharedConnection();
            }
        }

        /// <summary>
        /// 填充一个DataTable
        /// </summary>
        /// <param name="dt">DataTable的引用</param>
        /// <param name="sql">Sql语句</param>
        /// <param name="args">参数</param>
        public void Fill(DataTable dt, string sql, params object[] args)
        {
            OpenSharedConnection();

            try
            {
                using (var cmd = CreateCommand(_sharedConnection, sql, args))
                {
                    using (DbDataAdapter dbDataAdapter = _factory.CreateDataAdapter())
                    {
                        dbDataAdapter.SelectCommand = (DbCommand)cmd;
                        dbDataAdapter.Fill(dt);
                    }
                }
            }
            finally
            {
                CloseSharedConnection();
            }
        }

        #endregion

得到的DataTable可结合之前的一篇将DataTable转换为Json字符串的方法一起使用,无需转换实体,直接得到Json字符串,在前台使用。

posted @ 2012-06-20 16:39  拓荒者-NET  阅读(2832)  评论(1编辑  收藏