Set EF6 Code First strings fluently to nvarchar(max)

Jeremy Holovacs picture Jeremy Holovacs · Sep 19, 2015 · Viewed 15.8k times · Source

I'm building an EF6 code first model using the fluent API. My understanding is, by default, strings will be nvarchar(max), which (to be blunt) is dumb for a default. So I added the following convention code to set max default length to 255 characters:

modelBuilder.Properties<string>()
    .Configure(p => p.HasMaxLength(255));

Then I created a decorator like so:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TextAttribute : Attribute
{
}

I want to apply this to specific string properties that I actually want to be NVARCHAR(MAX).

What do I put in the fluent API to make sure all string properties with the [Text] decorator are built in the database with NVARCHAR(MAX)? I assume it would be something like this:

modelBuilder.Properties<string>()
    .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
    .Configure(p => p.HasMaxLength(?????));

Or am I doing this completely wrong?

Answer

RickNo picture RickNo · Jan 10, 2016

I don't know if you've found an answer by now, but in case anyone else is wondering how to do it, simply set the SQL datatype and ignore the HasMaxLength() invocation.

        modelBuilder.Properties<string>()
            .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
            .Configure(p => p.HasColumnType("nvarchar(max)"));

Using IsMaxLength() or HasMaxLength(null) would set the field to nvarchar(4000) (varchar(8000) if specifying the data type as varchar).