2

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?

Cleo
  • 620
  • 2
  • 10
  • 32

1 Answers1

0

try adding property as nullable:

public class UserAccount
{
    public int Id { get; set; }
    public string Username { get; set; }

    [Required]
    [DefaultValue(0)]
    public long? Number { get; set; } = 0; 
}

if you dont especified this, the database required a value for existed registers.

then run the application. and on Database asign the default value to existed registers directly with a sql script:

UPDATE {mytable} set Number=0 WHERE Number IS NULL;

change {mytable} to your table name

after this, if you need not nullable column remove the symbol "?" of long type propertie and run again

henoc salinas
  • 1,044
  • 1
  • 9
  • 20
  • This is a non-EF solution where manual interaction with the database is required; which is not practicable. My question is how to achieve my requirement using EF. It can't be that hard to add a non-nullable column to an existing database, can it? – Cleo Oct 06 '20 at 07:07
  • @Cleo i think it is a solution, because the restriction its in c# program, not in DB, when specified "Required", if the data is null, the program throw a exception, so you can have a nullable column in DB and the restriction is on EntityFramework – henoc salinas Oct 07 '20 at 14:27