Setting default global configuration for .NET types in Entity Framework

By default Entity Framework converts strings to nvarchar(MAX) in SQL Server which isn’t ideal.

We can configure this mapping in OnModelCreating on an entity by entity and property by property basis like so …


In the above case, we’ve set max length to be 255 and made the column to be a varchar type in SQL Server. Setting this for a lot of properties can be tedious.

Thankfully from Entity Framework 6, if we wish to set defaults for all properties of a certain type we can do this by overriding the ConfigureConventions DbContext method …


The code above will cause all strings to be set to varchar (on SQL Server) and to have a max length of 255 if they are not explicitly set in OnModelCreating.

In the case of the CategoryName property the explicit configurations in OnModelCreating match the global configs in ConfigureConventions so CategoryName will still be an nvarchar(255) …


If we look at the Badges entity however, we can see we have no Unicode explicit config set for BadgeName and Description …

… so the global config in ConfigureConventions takes affect and causes Entity Framework to create the columns as varchars. We can also see the global default length of 255 has not been applied …


Have you configured .NET type to DB mappings globally yet?

Leave a Reply

Your email address will not be published. Required fields are marked *