SQL column default value with Entity Framework

前端 未结 4 933
失恋的感觉
失恋的感觉 2020-12-17 10:09

I am trying to use Code-First EF6 with default SQL values.

For example, I have a \"CreatedDate\" column/property not null with a default in SQL of \"getdate()\"

4条回答
  •  盖世英雄少女心
    2020-12-17 10:30

    Accepted answer is correct for EF6, I'm only adding EF Core solution; (also my solution focuses on changing the default-value, rather than creating it properly the first time)

    There is still no Data-Attribute in EF Core.

    And you must still use the Fluent API; it does have a HasDefaultValue

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()
            .Property(b => b.Rating)
            .HasDefaultValue(3);
    }
    

    Note, there is also HasDefaultValueSql for NULL case:

            .HasDefaultValueSql("NULL");
    

    And you can also use the Migrations Up and Down methods, you can alter the defaultValue or defaultValueSql but you may need to drop Indexes first. Here's an example:

    public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME"
            );
    
            migrationBuilder.AlterColumn(
                name: "COLUMN_NAME",
                table: "TABLE_NAME",
                nullable: true,
                //note here, in the Up method, I'm specifying a new defaultValue:
                defaultValueSql: "NULL",
                oldClrType: typeof(int));
    
            migrationBuilder.CreateIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME",
                column: "COLUMN_NAME"
            );
        }
    
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME"
            );
    
            migrationBuilder.AlterColumn(
                name: "COLUMN_NAME",
                table: "TABLE_NAME",
                nullable: true,
                //note here, in the Down method, I'll restore to the old defaultValue:
                defaultValueSql: "0",
                oldClrType: typeof(int));
    
            migrationBuilder.CreateIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME",
                column: "COLUMN_NAME"
            );
    
    
        }
    }
    

提交回复
热议问题