Search code examples
c#ef-code-firstentity-framework-coreef-code-first-mapping

Set default value for multiple columns in a single statement


I'm using EF Core Code-First and need to set default value for multiple columns.

I know this is the statement for setting default for one column

modelBuilder.Entity<Registration>()
                        .Property(b => b.AdminFee)
                        .HasDefaultValue(25);

I have 10 fields with different default values and want to see if there is a short way to set default for all in one shot instead of repeating the above code 10 times.


Solution

  • You can use the Metadata API to achieve it. For example:

    var myProps = new Dictionary<string, object>()
    {
        { nameof(Registration.AdminFee), 25 },
        { nameof(Registration.AnotherProp1), 35 },
        { nameof(Registration.AnotherProp2), 18 },
        { ... }
    };
    
    foreach (var matchingProp in modelBuilder.Entity<Registration>()
                .Metadata
                .GetProperties()
                .Where(x => myProps.ContainsKey(x.Name)))
    {
        matchingProp.Relational().DefaultValue = myProps[matchingProp.Name];
    }