In my DbContext
class I have the following:
void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<string>().Configure(c => { c.HasMaxLength(250); });
}
but also inside the EntityTypeConfiguration
class for a specific model I have:
{
Property(p => p.Name).HasMaxLength(500);
}
The problem is that setting the property to 500 inside the Configuration class is not taking effect and EF is still validating the max to be 250.
How can I have a general setting of 250 but override by fluent api as needed inside each class?
If you want to give a string field 500 characters.
You can do this by using the "MaxLength" attribute.
I am creating a sample table like the following.
My Context Configuration.
void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<string>().Configure(c => { c.HasMaxLength(250); });
}
I am creating a table named FooEntity.
using System;
using System.ComponentModel.DataAnnotations;
namespace Foo.Model
{
public class FooEntity
{
[MaxLength(500)]
public string FooName { get; set; }
}
}
After adding this attribute, the migration output is as follows. Even if a 250 character limit is given, it will be passed as 500 characters in SQL.
CreateTable(
"dbo.FooEntity",
c => new
{
FooName = c.String(maxLength: 500)
});