6

When using EF Core we have the ability to set the default value on the property.

public class Foo
{
    public int Bar { get; set; }
}

public class FooConfiguration : IEntityTypeConfiguration<Foo>
{
    public void Configure(EntityTypeBuilder<Foo> builder)
    {
        builder.Property(s => s.Bar).HasDefaultValue(1337);
    }
}

When should we prefer using HasDefaultValue over initializing the default inside a class?

public class Foo
{
    public int Bar { get; set; } = 1337;

    // or inside constructor...
    // public Foo { Bar = 1337; }
}

Or should we do both? But in this case, HasDefaultValue seems redundant. It seems like a choice where you can choose only 1 option.

Konrad
  • 6,385
  • 12
  • 53
  • 96

2 Answers2

1

The HasDefaultValue() method specifies

The default value of a column is the value that will be inserted if a new row is inserted but no value is specified for the column.

Initializing the property with default value in the class will make all objects initialized of the class have the specified default value if not instructed otherwise. In your case, that means even non attached objects will have the default value, while using the HasValue() method will be used when inserting the object into the database. It also means, if there already is empty values in the database when you are adding the HasDefaultValue() method, they will not be overwritten.

kaffekopp
  • 2,551
  • 6
  • 13
-2

I don't know if I undestand right but you can use getter/setter methods for setting different default values for different properties like below,

 private int _bar = 1337;
 public int Bar{
     get{
         return _bar;
     }
     set{
         _bar = value;
     }
 }

 private int _secondBar = 1234;
 public int SecondBar{
     get{
         return _secondBar;
     }
     set{
         _secondBar = value;
     }
 }
Onur Tekir
  • 220
  • 1
  • 3