Set EF6 Code First strings fluently to nvarchar(max)

c# ef-code-first ef-fluent-api entity-framework

Question

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?

1
14
12/5/2019 6:57:57 PM

Accepted Answer

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).

20
1/14/2016 10:21:53 PM

Popular Answer

If you're doing it inside an EntityTypeConfiguration<MyEntity> class, it is similar to @RickNo's answer, but is done like this:

Property(x => x.MyVarcharMaxProperty)
    .HasColumnType("nvarchar(max)");


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow