Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting MaxLength for all strings in Entity Framework code first

I'm developing a code-first database, using Entity Framework 6.

I know I can set [MaxLength(myLen)] on the property of a model.

What I wondered, is if this is possible to do in a filter or a custom attribute, so that all strings take on a default, of say 250, unless specified directly on the property.

Failing this, is there a way to change the default of nvarchar(max)?

like image 230
Darren Wainwright Avatar asked Dec 01 '22 02:12

Darren Wainwright


2 Answers

Entity Framework introduced Custom Code First Conventions for this in 6.1

modelBuilder.Properties<string>()
            .Configure(c => c.HasMaxLength(250));

Conventions operate in a last wins manner and the Fluent API and Data Annotations can be used to override a convention in specific cases

like image 156
Colin Avatar answered Dec 06 '22 01:12

Colin


You can do this, which ensures all strings are the maximum length supported by the database provider:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<string>().Configure(p => p.IsMaxLength());
    }

Add this method (or modify the existing one) in your DbContext class.

like image 35
greg84 Avatar answered Dec 06 '22 01:12

greg84