一个顶N个的NextResult
在大多数网站的开发中,很多功能都是模块化了的,方便统一和管理,用户控件显然是个不错的选择!我们常常会有很多栏目,封在用户控件里面,都是用来读取每个栏目的记录,每个控件的数据读取都是独立的,也就是说,这个页面有多少个这样的用户控件,就要建立多少个数据库连接,非常耗费资源!虽然用户控件可以用缓存,但是毕竟效率没有一次性读取的效率高!所以想了想,发现用DataReader的NextResult可以实现这样的效果!
首先是一个控件绑定的Helper:
首先是一个控件绑定的Helper:
public class ListBinder
{
private List<Repeater> _controllist=new List<Repeater>();
public List<Repeater> Controllist
{
get { return _controllist; }
}
public void BindAll(IDataReader dr)
{
int length=this._controllist.Count;
for (int i = 0; i < length;i++ )
{
if (i == 0)
{
_controllist[i].DataSource = dr;
_controllist[i].DataBind();
}
else
{
if (dr.NextResult())
{
_controllist[i].DataSource = dr;
_controllist[i].DataBind();
}
}
}
}
}
接下来是测试调用的代码:{
private List<Repeater> _controllist=new List<Repeater>();
public List<Repeater> Controllist
{
get { return _controllist; }
}
public void BindAll(IDataReader dr)
{
int length=this._controllist.Count;
for (int i = 0; i < length;i++ )
{
if (i == 0)
{
_controllist[i].DataSource = dr;
_controllist[i].DataBind();
}
else
{
if (dr.NextResult())
{
_controllist[i].DataSource = dr;
_controllist[i].DataBind();
}
}
}
}
}
string sql = "select top 5 * from [CaseShow] where [CategoryId]=9;select top 5 * from [CaseShow] where [CategoryId]=10;select top 5 * from [CaseShow] where [CategoryId]=11;select top 5 * from [CaseShow] where [CategoryId]=12";
using (IDbConnection con = AFrameWork.Data.DataFactory.GetConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try
{
IDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
con.Open();
using (IDataReader dr = cmd.ExecuteReader())
{
ListBinder lb = new ListBinder();
lb.Controllist.Add(rpZhuanti);
lb.Controllist.Add(rpAd);
lb.Controllist.Add(rpHunli);
lb.Controllist.Add(rpPs);
lb.BindAll(dr);
}
}
catch
{
con.Close();
throw;
}
这里一次性读了四个栏目出来,只建立了一个数据库连接,比原来的效率和性能要好很多!不过这里对于结果集和控件的绑定对应就要自己控制了,当然我相信聪明的你会有办法搞定的,呵呵!
using (IDbConnection con = AFrameWork.Data.DataFactory.GetConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try
{
IDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
con.Open();
using (IDataReader dr = cmd.ExecuteReader())
{
ListBinder lb = new ListBinder();
lb.Controllist.Add(rpZhuanti);
lb.Controllist.Add(rpAd);
lb.Controllist.Add(rpHunli);
lb.Controllist.Add(rpPs);
lb.BindAll(dr);
}
}
catch
{
con.Close();
throw;
}