如何修改以下方法以返回List<数据表>还是DataSet?我想使它通用,因此它可以从数据库返回多个结果集。
public static DataTable ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
var dt = new DataTable();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
reader.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dt;
}
答案 0 :(得分:9)
我最终这样做了 -
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var connectionString = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
var ds = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
}
}
return ds;
}
答案 1 :(得分:2)
reader.NextResult()应该在技术上有用。这是修改后的版本:
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
DataSet dataSet = new DataSet();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
do
{
DataTable dt = new DataTable();
dt.Load(reader);
dataSet.Tables.Add(dt);
}
while (reader.NextResult());
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dataSet;
}