2

I'm debugging an intermittent truncation error in my application. The error in my logs looks like this:

System.Data.SqlClient.SqlException: String or binary data would be truncated.
The statement has been terminated. Generated: Tue, 02 Nov 2010 03:55:18 GMT

NHibernate.Exceptions.GenericADOException: could not insert:
[DataModel.Product][SQL: INSERT INTO [Product] (Fields) VALUES (?, ?,...);
select SCOPE_IDENTITY()] ---> 
System.Data.SqlClient.SqlException: String or binary data would be truncated. 
The statement has been terminated.    
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)

Notice that the error does not provide parameter values for the sql that threw the error, only placeholders: (?, ?,...). Is there a way to get these from nHibernate? Something like this:

try {
    ...
    Session.Flush(); // throws
}
catch (GenericADOException ex) {

    // want to get the bad parameter values, 
    // so I can re-throw a more helpful exception
}

5 Answers 5

6

Most of the time, this string or binary data truncated.... comes from Nhibernate Ado exception when data being fed has more characters than the field length. e.g. if a table db field is nvarchar(50), but an effort is being made to insert more than 50 characters, this exception occurs. solution is to either increase the table Db field length or reduce the data characters being inserted.

Sign up to request clarification or add additional context in comments.

Comments

3

You could setup an IPreInsertEventListener that loops through the string properties prior to insertion, checking their length.

If one of the properties is too long, you can log the name of the property and its value.

Comments

2

You can configure log4net to send NH SQL output somewhere. Example:

<log4net>
  <appender name="Debug" type="log4net.Appender.DebugAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %message%newline" />
    </layout>
  </appender>
  <logger name="NHibernate.SQL">
    <level value="DEBUG"/>
    <appender-ref ref="Debug"/>
  </logger>
</log4net>

In this case, I'm sending it to the Debug window.

Comments

1

You might be able to drill down and find out what it's doing with nHibernate Profiler.

Comments

0

The best solution seems to be event listener that validate values used in SQL (it works independently of DB, even with SQLite which ignores length constrains). I wrote a blog post with description how to implement such listener https://cezarypiatek.github.io/post/validate-fields-in-nhibernate-model/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.