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.
Looking at the code for FileHelpers 2.9.9, the FileHelpers error handling does not seem to have been implemented for the
DatabaseStorageclass which is the base class forSqlServerStorage. I think the reason is probably, that the SQL statements are handled as in batches for performance reasons, so it is not possible tocatchan individual record’s error.It would not be too difficult to add the missing error-handling by overriding
InsertRecords(Object[]), but unfortunatelySqlServerStorageissealedand some of the helper routines areinternal, so you’d end up having to copy several classes into your code. (If you do this, make sure that you setExecuteInBatchto 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 theInsertRecords()call, but this would not prevent errors occurring for other reasons.