Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set EF6 Code First strings fluently to nvarchar(max)

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?

like image 888
Jeremy Holovacs Avatar asked Sep 19 '15 00:09

Jeremy Holovacs


4 Answers

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

like image 158
RickNo Avatar answered Nov 17 '22 08:11

RickNo


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)");
like image 42
Katie Kilian Avatar answered Nov 17 '22 07:11

Katie Kilian


There is a method to indicate that you use the maximum allowed by the database.

IsMaxLength ()

    modelBuilder.Properties<string>()
        .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
        .Configure(p => p.HasColumnType("nvarchar").IsMaxLength());
like image 7
Dionny Prensa Avatar answered Nov 17 '22 06:11

Dionny Prensa


You can use HasColumnType

enter image description here

or you can use without any HasColumnType or HasMaxLength. There is no need to use HasMaxLength

enter image description here

like image 3
Ergin Çelik Avatar answered Nov 17 '22 06:11

Ergin Çelik