1

So I have an NHibernate mapping file with the following property:

<property name="FullName" column="FullName" type="string" not-null="true" />

If I set the length="50" for example, NHibernate will truncate the string when inserting into the database. If I remove the length property, that database throws the exception like it should; saying that it cannot insert the record. Is this normal behavior? If so, what is the purpose of the length property. Perhaps I've configured NHibernate incorrectly or am not appreciating the situation. Any thoughts/ideas would be great.

1 Answer 1

5

Length property is used to create a database from the model/mappings when you are using schema exporter.

If you are looking for string length validation during persistence, take a look at the NHibernate.Validator project.

http://nhforge.org/blogs/nhibernate/archive/2009/05/01/nhibernate-validator.aspx

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

2 Comments

The reason I caught the issue was because I was writing a unit test to test that the insert would fail if the string length of FullName exceeded 50 characters. It did not fail and truncated the string before inserting into the database. As soon as I removed the length attribute in the mapping file, it did fail.
NHibernate (just like any other ORMs) uses parameterized queries. When you set a string length of 50 for a field/property, it uses nvarchar(50) instead of nvarchar(4000). It causes the strings to be truncated instead of failing.

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.