Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultValue in migration doesn't work

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.

like image 564
TamarG Avatar asked Apr 27 '26 14:04

TamarG


2 Answers

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"

like image 186
Mike Avatar answered Apr 30 '26 05:04

Mike


Ok... Use like below

AddColumn("dbo.Props", "Prop2", c => c.Int(nullable: false, defaultValue: 0));

set nullable:false in your code

like image 27
Mukesh Kumar Avatar answered Apr 30 '26 05:04

Mukesh Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!