简体   繁体   中英

DataSet.Load(reader) error “Table TableName does not belong to this DataSet.”

i am trying to fill dataset (more then one datatables from db in one go) using system.data.common.dbcommand. but not successful. I am getting error "Table TableName does not belong to this DataSet."

Note: TableName is name of datatable. Here is my code, please guide and help me.

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;
    }

I have consulted http://msdn.microsoft.com/en-us/library/5fd1ahe2.aspx but couldn't get where I am wrong. Please help me.

Thanks a lot

you are overriding the dataset definition in this code block

 try
        {
            command.Connection.Open();
            DbDataReader reader = command.ExecuteReader();
            **ds = new DataSet ();**
            ds.Load (reader, LoadOption.OverwriteChanges,tables);
        }

put it in this way:

try
        {
            command.Connection.Open();
            DbDataReader reader = command.ExecuteReader();
            //**ds = new DataSet ();**
            ds.Load (reader, LoadOption.OverwriteChanges,tables);
        }

greetings!!

Check the overloads of the ds.Tables.Add method. Make sure when you add the table, a table name is being specified, otherwise it might just add it with a default name, such as 'TableName'.

Good luck!

Just a comment (Needed more room!) -

Please don't do this:

...
catch (Exception ex)
{ throw ex; }
...

http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx

http://msdn.microsoft.com/en-us/library/seyhszts.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM