Orchard NHibernate Truncate and StringLengthMax

Orchard NHibernate Truncate and StringLengthMax

Here is a tip for all Orchard Developers. When you are building a ContentPart and ContentPartRecord during Orchard Module development, you may need to use the StringLengthMax Attribute on ContentPartRecord Properties to keep NHibernate from truncating strings when saving data to the SQL Server Database. If you don't, you will often see NHibernate errors in Orchard CMS log files mentioning string was too long and truncated. Unfortunately, this NHibernate error in Orchard keeps the ContentPart and Content Type from being saved and the only way to notice the problem is to view the Orchard log files.

Orchard NHibernate String Truncate Errors

If you take a peek at the BodyPartRecord in Orchard CMS, you will notice that it has a StringLengthMax Attribute on the Text Property

public class BodyPartRecord:ContentPartVersionRecord {
    [StringLengthMax]
    public virtual string Text { get; set; }

    public virtual string Format { get; set; }
}

The StringLengthMax Attribute tells NHibernate that the length of the string in Text can be more than 4000 characters and not to truncate it. Without the attribute, NHibernate will assume the Text Property can only be 4000 characters and will throw a truncate error if the string is more than 4000 characters. The truncate error will show up in your Orchard Log Files.

Therefore, if you are an Orchard Developer creating your own ContentPartRecords with string properties and these properties can be longer than 4000 characters, you need to make sure you add the StringLengthMax Attribute to the property to give NHibernate a heads-up!

Conclusion

This is just a quick Orchard Tutorial for those new Orchard Developers that are experiencing an NHibernate string truncate error for their ContentPartRecord and don't have a clue why it's happening.

If you need help on your next Orchard CMS Projects, I am an Orchard Developer available for hire.