I get SqlCeException ... The column cannot contain null values. [ Column name = Subtotal
when I run the following Entity Framework migration.
public override void Up()
{
AlterColumn("BuildingOrders", "Subtotal",
c => c.Decimal(nullable: false, precision: 18, scale: 2));
}
Is this the right way to set the default value? It seems too easy 🙂
public override void Up()
{
AlterColumn("BuildingOrders", "Subtotal",
c => c.Decimal(nullable: false, precision: 18, scale: 2, defaultValue: 0));
}
I tried this after seeing a similar question for ruby on rails.
It doesn’t work this way. You set default value in database but it is not used. You cannot define your property as nullable in class when mapped column is not nullable. Default value in database is applied only if you don’t insert any value into that column but EF always inserts value to all columns which are not database generated (in turn values for database generated columns cannot be defined in the application) so in this case you defined your property as nullable and EF inserts null explicitly => exception.