Will entity fill default values into db?

asp.net-core-2.0 c# entity-framework-core sql-server

Question

I had a nullable field in my model. I changed it to be required and non-nullable. New records get set correctly, but is there anyway to have existing records have their field be updated?

In the context file I have the following:

builder.Entity<Player>()
    .Property(p => p.Notifications)
    .HasDefaultValue(NotificationPreference.Both);

EDIT:

So if I manually do an ef migration on localhost all the fields are updated correctly. Is there a way I can do this from the azure portal? I was under the impression that this would be done automatically. But it doesn't seem like it does.

1
0
6/21/2018 2:39:08 AM

Accepted Answer

If you must update the values for other code to work, then do it directly on the SQL server as a one-off.

If you write code to automatically run through and set every time it's hit, you run the risk that months from now that code will be forgotten and may eventually produce an outcome you don't want (it's also inefficient)

A better way to handle this may be to set the default value in the get of the property by the ?? coalescing operator if EF sets a null, allowing the property to remain read-write, but with a backing field. This approach makes it explicit to others what the default value is.

A sample of a class with a property with a backing field:

public class Person
{
  private int? age;

  public int? Age
  {
    get
    {
       return this.age ?? -1; // if (Age == 0) would be true otherwise as default(int) would be used
    }

    set
    {
       this.age = value;
    }
  }
}
1
6/21/2018 10:57:51 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