HasDefaultValue vs setting default value from the constructor

c# ef-core-2.1 entity-framework-core

Question

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.

1
1
10/29/2018 9:15:44 AM

Popular Answer

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.

1
10/29/2018 9:29:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow