When using the automapping feature of Fluent NHibernate you may encounter some problems when storing large text data in the database. Below is a class which gets mapped by the automapper in Fluent NHibernate. Both Title and TextContent are strings. The difference between them is that the TextContent property might store a large chunk of text.

image

The default automapper in Fluent NHibernate will create a table with a nvarchar(255) column for both the Title and TextContent. This is fine for most cases but in this case the TextContent property may contain much more than 255 characters. Trying to save the entity with more than 255 characters stored in TextContent will give throw an exception saying:

System.Data.SqlClient.SqlException: String or binary data would be truncated.
The statement has been terminated.

This is the same problem you might run into when using Castle ActiveRecord which also will do a default nvarchar(255) for a string property. It's quite simple to override the default automapper in Fluent NHibernate to change the column in the database into a text type for example. All you need to do is create a class which implements the interface IAutoMappingOverride<T> and add it to the configuration.

   1: public class HeadlineOverride : IAutoMappingOverride<Headline>
   2: {
   3:         public void Override(AutoMap<Headline> mapping)
   4:         {
   5:             mapping.Map(t => t.TextContent).CustomTypeIs("StringClob").CustomSqlTypeIs("text");
   6:         }
   7: }


All you need to do a manual mapping of the field and set the custom type to StringClob and SqlType to text. All the other properties will still be mapped by the automapper in Fluent NHibernate. To make sure that Fluent NHibernate will load the override into the configuration you need to set it up.

   1: return AutoPersistenceModel
   2:        .MapEntitiesFromAssemblyOf<Headline>()
   3:        .Where(t => t.Namespace == "Incendi.Models")
   4:        .UseOverridesFromAssemblyOf<HeadlineOverride>();

On line #4 it tells the automapper to use the overrides from the assembly where HeadlineOverride is declared. If you drop/create the schema with this updated configuration you'll end up with a text type on the TextContent column instead of a varchar(255).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading