Search code examples
c#.netentity-framework.net-coreentity-framework-core

DefaultValueAttribute appears to have no effect


I added the DefaultValueAttribute to an existing column.

[DefaultValue(0)]
public double Volume { get; set; }

But it doesn't appear to make any difference. I couldn't find anything in the generated migration code for this column. And no default value shows in SSMS.

enter image description here

Does anyone know why this attribute doesn't appear to be supported? Is it necessary to use OnModelCreating() instead?


Solution

  • DefaultValue attribute has no effect in EF Core (currently). I cannot say "why", but you can see that the official EF Core documentation for Default Values shows only fluent API configuration (HasDefaultValue and HasDefaultValueSql) and no data annotations as for other mappings which have such.

    Note that EF Core is evolving and each new version adds some data annotations, so this might change in the future (even though I don't see such a plan for default values). So for now, fluent API is the only option.