Search code examples
c#sql-serverfilehelpers

FileHelpers and SQL Insert with SqlServerStorage class ---How to show errors


I am using the FileHelpers libraries to upload a CSV file to SQL Server. I would like to present the user with a list of records which could not be uploaded do to errors. I am setting the ErrorMode of the SqlServerStorage class to SaveAndContinue, however the InsertRecords method still throws an exception when one of the records violates a foriegn key constraint. Is there a way to save this error and continue with the insert?

SqlServerStorage storage = new SqlServerStorage(typeof(RouteRecord),ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString);
storage.ErrorManager.ErrorMode = FileHelpers.ErrorMode.SaveAndContinue;
storage.InsertRecords((RouteRecord[])Session["successfulRecordArray"]);

Thanks.


Solution

  • Looking at the code for FileHelpers 2.9.9, the FileHelpers error handling does not seem to have been implemented for the DatabaseStorage class which is the base class for SqlServerStorage. I think the reason is probably, that the SQL statements are handled as in batches for performance reasons, so it is not possible to catch an individual record's error.

    It would not be too difficult to add the missing error-handling by overriding InsertRecords(Object[]), but unfortunately SqlServerStorage is sealed and some of the helper routines are internal, so you'd end up having to copy several classes into your code. (If you do this, make sure that you set ExecuteInBatch to false, so that each SQL statement gets processed individually - this will affect performance).

    Alternatively, you could implement some check for foreign key violations (e.g., by enumerating RouteRecord[]) in a separate routine which is called before the InsertRecords() call, but this would not prevent errors occurring for other reasons.