NHibernate and nvarchar(MAX)

Been using NHibernate on my most recent project and the team and I have spent a bit of time trying to figure out how to get around the fact that NHibernate generates all strings as nvarchar(255) by default. We’re also using Attributes for our NHibernate mappings (NHibernate.Mapping.Attributes). The solutions is actually quite simple.

private string _myString;

[Property(length = 4001)]
public string MyString
{
get { return _myString; }
set { _myString = value; }
}

Setting the length to anything over 4000 forces NHibernate to generate the DB schema with a DB type of nvarchar(MAX).

I’ve only tested this with the SQL 2005 dialect (Dialect.MsSql2005Dialect)

Advertisements

6 Responses to NHibernate and nvarchar(MAX)

  1. Alex says:

    Thanks my friend, this really helped!

  2. Alex says:

    BTW, it creates a “ntext” field for the MsSql2000Dialect

  3. René says:

    Any idea why persisting data with unicode characters goed wronge? The characters appear as ? in Sql server 2008.

    I use nvarchar(max) and in my mapping I specified data type AnsiString, and use ordinary String type in my data objects.

    Also I set NHibernate.Dialect.MsSql2005Dialact as the dialect in my nHibernate configuration.

    When I insert it manually using the MSSQL client tools, using something like insert into table values (N’My Unicode string ChãräctérTèst’)

    It does work, but not with nHibernate..

  4. I’m not in front of my dev machine right now, but have you tried using String instead of AnsiString?

  5. Quandary says:

    @René: It’s a known bug in nHibernate < 3.0

  6. Quandary says:

    @René: It’s when you forget the N in front of the ‘. N as in Nvarchar, N like uNicode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: