markrendle / Simple.Data

A light-weight, dynamic data access component for C# 4.0
MIT License
1.33k stars 303 forks source link

Records with different columns break SqlBulkInserter. #338

Open mattrrichard opened 10 years ago

mattrrichard commented 10 years ago

SqlBulkInserter makes 2 bad assumptions about the records it gets in a bulk insert:

  1. All records contain the same columns (or at least that the first record has all of the columns since only the first is used to generate the data table and all 'optional' columns are at the end)
  2. Calling record.Values.ToArray() will yield the same column ordering on all records.
dynamic r1 = new SimpleRecord();
r1.FirstName = "Bob";
r1.LastName = "Dole";

dynamic r2 = new SimpleRecord();
r2.FirstName = "Bob";
r2.MiddleInitial = "L";
r2.LastName = "Saget";

db.People.Insert(new [] {r1, r2});

In the example above, when SqlBulkInserter tries to add the row for r2 with dataTable.Rows.Add(record.Values.ToArray()) it will generate an exception stating "input array is longer than the number of columns" because the table only has 2 columns.

If, however, you passed the records in the other order (db.People.Insert(new [] {r2, r1})), It wouldn't error, but r1's data wouldn't be correctly inserted: "Dole" would be in the MiddleInitial column instead of Last Name because the order of adding those values to the record effects the order of the values in the ToArray call.