4

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.

FLICKER
  • 6,439
  • 4
  • 45
  • 75
  • 1
    What is wrong with repeating it 10 times for different columns? This is still will be used only once. if default values are part of the business logic, then move it from database to business layer responsibility where you can do it dynamically – Fabio Oct 21 '17 at 19:47
  • Nothing is wrong with that. I just want to know if there is any way to have less code and improve my knowledge. – FLICKER Oct 21 '17 at 19:50
  • Is this EntityFramework or EntityFrameworkCore? – haim770 Oct 21 '17 at 19:55
  • As I've mentioned in tags, it is Core – FLICKER Oct 21 '17 at 19:55
  • _if there is any way to have less code_ - "less code" not always mean better readability or maintenance – Fabio Oct 21 '17 at 20:29
  • I agree that less code is not better most of the time – FLICKER Oct 21 '17 at 20:32

1 Answers1

2

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];
}
FLICKER
  • 6,439
  • 4
  • 45
  • 75
haim770
  • 48,394
  • 7
  • 105
  • 133
  • Thank you for response. Maybe I was not clear. Default values are not the same for each field. so you answer is not exactly what I'm looking for but it I think you may have another solution by extending your answer. – FLICKER Oct 21 '17 at 20:10
  • looks interesting. I'll try that will will update you. Thanks. – FLICKER Oct 21 '17 at 20:14
  • With this approach you loose benefits of "renaming" tools. – Fabio Oct 21 '17 at 20:28
  • @Fabio, There you go – haim770 Oct 21 '17 at 20:29
  • Worked well. I decided to go the longer method (repeating the code 10 time). This answer was informative though. Thank you! – FLICKER Oct 21 '17 at 20:39