Using Entity Framework 6 with code-first, I have an existing entity class like this:
public class UserAccount
{
public int Id { get; set; }
public string Username { get; set; }
}
So far, so good. Several accounts were inserted successfully into the database. Now, based on a new requirement, I'ld like to add a new field of type "long" with a default value of "0". So it must be non-nullable. Up until today I thought "That's what Data Annotations are for!". So I added this to the class:
[Required]
[DefaultValue(0)]
public long Number { get; set; } = 0;
With auto-migrations enabled, I started the application and promptly got an exception saying: "The property 'Number' on 'UserAccount' could not be set to a 'null' value". Upon investigating the database via SQL Server Management Studio, the problem is clear: EF auto-created a nullable "bigint" column without default value.
On other entities, attributes like [Required] or [MaxLength()] work just fine.
Why does EF ignore my data annotations in this case? What's the proper way to add a new property/column with a default value?