Search code examples
entity-frameworkef-code-first

How can I set AllowEmptyStrings for all Code First Required strings?


I can decorate an individual string in a model with this attribute -

[Required(AllowEmptyStrings= true)]

How can I do this for all Required strings from OnModelCreating?

Note I do not want to turn validation off like this -

mDbContext.Configuration.ValidateOnSaveEnabled = false;

Solution

  • Unfortunately I think the answer to this is that you can't.

    In the FluentAPI you can use a custom convention that will apply across the entire context:

    //All strings are required
    modelBuilder.Properties<string>()
        .Configure(p => p.IsRequired());
    
    //All strings named "Foo" are required and have a maximum length
    modelBuilder.Properties<string>()
        .Where(p => p.Name == "Foo")
        .Configure(p => p.IsRequired().HasMaxLength(256));
    
    //All strings with a "Required" attribute have a maximum length:
    modelBuilder.Properties<string>()
        .Where(p => p.CustomAttributes
                    .Where(a => a.AttributeType == typeof(RequiredAttribute))
                    .Any())
        .Configure(p => p.HasMaxLength(256));
    

    The problem is that the Fluent API doesn't give access to an "AllowEmptyStrings" property. It has probably been designed with configuring the database in mind. And checking for empty strings is validation that would normally be done before the data gets to the database

    Reference: Custom Conventions