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

北城以北 提交于 2019-12-12 01:43:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8900906/filehelpers-and-sql-insert-with-sqlserverstorage-class-how-to-show-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!