I have an MVC project with EF and code-first.
I have a model PropBase and a model MyProp - and they are mapped to the same table (with an automatically "Discriminator" column).
I added two properties to MyProp - prop1 and prop2:
public class PropBase
{
public double Prop0 { get; set; }
}
public class MyProp: PropBase
{
public double Prop10 { get; set; }
public double Prop1{ get; set; } // new property
public int Prop2{ get; set; } // new property
}
And I also added a new migration:
public partial class AddProps12 : DbMigration
{
public override void Up()
{
AddColumn("dbo.Props", "Prop1", c => c.Double(nullable: true, defaultValue: 0));
AddColumn("dbo.Props", "Prop2", c => c.Int(nullable: true, defaultValue: 0));
}
public override void Down()
{
DropColumn("dbo.Props", "Prop1");
DropColumn("dbo.Props", "Prop2");
}
}
but when I run the application - the new columns are added with null and on the line
return m_myPropsRepository.AsQueryable().ToList();
I get this error
The 'Prop1' property on 'MyProp' could not be set to a 'null' value. You must set this property to a non-null value of type 'Double'.
I can't use nullable:false, because when I insert a new PropBase to the table - it doesn't know Prop1 and Prop2 and therefore inserts NULL and then I get an error because I defined it as non-nullable.
I need a way to do it nullable AND to put 0 as default value to the current MyProp rows.
Please try
AddColumn("dbo.Props", "Prop1", c => c.Double());
AddColumn("dbo.Props", "Prop2", c => c.Int());
Sql("UPDATE dbo.Props SET Prop1 = 0, Prop2 = 0 WHERE Discriminator = 'MyProp'");
The idea is to update with not null value the old values from DB table with Discriminator "MyProp"
Ok... Use like below
AddColumn("dbo.Props", "Prop2", c => c.Int(nullable: false, defaultValue: 0));
set nullable:false in your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With