none
MissingSchemaAction.AddWithKey + dataTable.Rows.Add = NullReferenceException? Bug? RRS feed

  • Question

  • Suppose we have the following table:

     

    Code Block

    CREATE TABLE [dbo].[Temp](

    [ItemId] [int] NOT NULL,

    [Region] [varchar](250) COLLATE Latin1_General_CI_AS NULL,

    CONSTRAINT [PK_Temp2] PRIMARY KEY CLUSTERED

    (

    [ItemId] ASC

    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

    ) ON [PRIMARY]

     

     

    Now let's try and get an empty datatable matching the schema of this one. delete the primary key column and then try to add a couple of rows.

     

    Code Block

    //Get an empty datatable

    table = new DataTable();

    SqlDataAdapter adapter = new SqlDataAdapter("Select Top 0 * from Temp", "connectionstring goes here...");

    adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

    adapter.Fill(table);

     

    //Remove the primary key column

    table.PrimaryKey = new DataColumn[0];

    table.Columns.RemoveAt(0);

     

    //Try to add a couple of rows

    DataRow row = table.NewRow();

    table.Rows.Add(row); // <--- First row is added ok

    row = table.NewRow();

    table.Rows.Add(row); // <---BAM: NullReferenceException

     

     

     

    I understand there are workarounds, (i.e. just select the columns you need) But i thought i would make you aware of this issue. (this is on VS2005 and .Net v2.0.50727)


    Now the above code will work fine  if the line

      adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

    is removed

     

    Why does the code fail if i dont remove the MissingSchemaAction.AddWithKey?

    Is this a bug, or is this the intended behaviour?

     

    Thanks,

    Anastasiosyal

    Friday, October 19, 2007 12:44 PM

Answers