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?
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).
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)");
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());
You can use HasColumnType
or you can use without any HasColumnType or HasMaxLength. There is no need to use HasMaxLength
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With