我需要通过ADO.Net优化我的数据访问。对于项目的复制,我不能使用Linq或实体......
所以我推出了15个独立的ADO.NET查询。我遵循标准,打开连接,启动查询,使用DataReader获取数据,将它们存储在类中,最后我关闭连接......
但我觉得这个项目不够快。所以,伙计们,你能告诉我一些提高速度的技巧吗?
我的数据库是SQL Server,尽我所能,我按实体推送查询。
编辑:
private void Connect(string comando) {
try {
string cadena = "connection_data";
Cn = new SqlConnection(cadena);
Cn.Open();
SqlCommand Com = new SqlCommand(comando, Cn);
Datos = Com.ExecuteReader();
}
catch (Exception e)
{
//
}
}
private void Close()
{
try
{
Cn.Close();
Datos.Close();
}
catch (Exception e)
{
//
}
}
public List<class1> getClass1(double id)
{
Connect("SELECT TOP (5) CASE WHEN [table1].[attribute1] IN (7, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29) THEN 'random_name' " +
"WHEN [table1].[attribute3] = NULL AND [table1].[attribute2] = NULL THEN 'random_name2' WHEN [table1].[attribute3] = NULL THEN [table1].[attribute3] ELSE "
// bla bla bla bla and so on and I have 15 massive queries like this one;
List<class1> res = new List<class1>();
if (Datos.HasRows == true)
{
while (Datos.Read())
{
class1obj = new class1();
obj.at1= class1.cont + 1;
obj.at2= class1.cont + 1;
class1.cont++;
obj.at3= "random_value";
obj.at4= Datos.GetValue(0);
obj.at5= Datos.GetValue(1);
res.Add(obj);
}
Close();
}
return res;
}
答案 0 :(得分:1)
如果你有为每个班级创作的功能,那么你可以做的是这样的:
没有函数getClass1
有一个接口:
public interface IBuildClass<TClass>
{
Task<IEnumerable<TClass>> BuildAsync(double id);
}
为接口添加一个基类,该接口将作为依赖关系请求数据库的连接对象
public abstract class BuildClassBase<TClass> : IBuildClass<TClass>
{
public BuildClassBase(SqlConnection connection)
{
Connection = connection;
}
public async Task<IEnumerable<TClass>> BuildAsync(double id)
{
//Execute query and pass results to InnerBuid
return InnerBuildAsync(/*Pass DataTable*/);
}
public abstract async Task<IEnumerable<TClass>> InnerBuildAsync(DataTable data);
//Ctor of each derived class will set the value
public string Query { get; protected set; }
public SqlConnection Connection {get; set; }
}
然后是一个特定的实现,匹配您要创建的每个类。您也可以为它们添加工厂:
public interface IBuildClassFactory
{
IBuildClass<TClass> GetBuilder<TClass>();
}
然后在您当前执行所有15种方法的代码中,您可以为每个类创建Task
,然后await buildClassFactory.GetBuilder<ClassA>().BuildAsync(id)
。类似的东西:
double id = 1;
Task createClassA = buildClassFactory.GetBuilder<ClassA>().BuildAsync(id);
Task createClassB = buildClassFactory.GetBuilder<ClassB>().BuildAsync(id);
Task createClassC = buildClassFactory.GetBuilder<ClassC>().BuildAsync(id);
....
Task.WaitAll(createClassA, createClassB, createClassC....);
//And then get result from tasks