我正在尝试使用 system.data.common.dbcommand。来填充数据集(一次性使用db中的多个数据表)但不成功。我收到错误“表 TableName 不属于此DataSet。”
注意: TableName 是datatable的名称。这是我的代码,请指导和帮助我。
dbCommand = DBHelper.CreateCommand("SPName");
DataTable EmailMessage=new DataTable ();
DataTable EmailContact=new DataTable ();
DataTable EmailAttachment=new DataTable ();
EmailAttachment.TableName = "EmailAttachment";
EmailContact.TableName = "EmailContact";
EmailMessage.TableName = "EmailMessage";
DataTable[] tables = {EmailMessage,EmailContact,EmailAttachment};
DataSet ds= DBHelper .ExecuteDataSet(dbCommand,tables);
public static DataSet ExecuteDataSet(DbCommand command,DataTable[] tables)
{
DataSet ds = new DataSet();
foreach (DataTable dt in tables)
{
ds.Tables.Add(dt);
}
try
{
command.Connection.Open();
DbDataReader reader = command.ExecuteReader();
ds = new DataSet ();
ds.Load (reader, LoadOption.OverwriteChanges,tables);
}
catch (Exception ex)
{ throw ex; }
finally
{ command.Connection.Close(); }
return ds;
}
我咨询了http://msdn.microsoft.com/en-us/library/5fd1ahe2.aspx,但无法解决我的错误。请帮帮我。
非常感谢
答案 0 :(得分:2)
您正在覆盖此代码块中的数据集定义
try
{
command.Connection.Open();
DbDataReader reader = command.ExecuteReader();
**ds = new DataSet ();**
ds.Load (reader, LoadOption.OverwriteChanges,tables);
}
这样说:
try
{
command.Connection.Open();
DbDataReader reader = command.ExecuteReader();
//**ds = new DataSet ();**
ds.Load (reader, LoadOption.OverwriteChanges,tables);
}
问候!!
答案 1 :(得分:0)
检查ds.Tables.Add方法的重载。确保在添加表时,指定了表名,否则可能只是添加默认名称,例如“TableName”。
祝你好运!答案 2 :(得分:-1)
只是评论(需要更多空间!) -
请不要这样做:
...
catch (Exception ex)
{ throw ex; }
...
http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx