EF6 Oracle default value for a column in code firs

2019-08-14 19:04发布

问题:

I am trying to write a migration that sets Default Value for a NUMBER column in my Oracle database using EntityFramework 6. Here is my first try that didn't set the default value:

    public override void Up()
    {
        AddColumn("MTA.PLAN_SHEETS", "QUANTITY_CHANGED", c => c.Decimal(nullable: true, precision: 3, scale: 0, defaultValueSql: "1"));
    }

I also tried to use defaultValue instead of defaultValueSql and again it didn't set the default value for the column.
Is there anything wrong with my migration code?

回答1:

I came across the same problem working with Oracle and EF6. It would appear the Oracle provider does not support it. There is a work around though, in case you haven't already found one.

You first need to set the QuantityChanged property as nullable in your model (or Fluent API, wherever you are handling this). Then you can run the add-migration command which will generate a migration file with the 'AddColumn' method in the 'Up' method. After that, add an explicit SQL command to update all values to the default value needed. If you need the column to be NOT NULL moving forward you will need another SQL command to modify the column and set it to NOT NULL.

    public override void Up()
    {
        AddColumn("MTA.PLAN_SHEETS", "QUANTITY_CHANGED", c => c.Decimal(precision: 3, scale: 0));
        Sql("UPDATE MTA.PLAN_SHEETS SET QUANTITY_CHANGED = 1");
        Sql("ALTER TABLE MTA.PLAN_SHEETS MODIFY QUANTITY_CHANGED NOT NULL");
    }

I hope this helps. Reference my question if needed: How do I set a default value for a new column using EF6 migrations?