D
D
DailyDDose2018-02-11 18:47:21
ASP.NET
DailyDDose, 2018-02-11 18:47:21

EntityFrameWork - migration to add a column?

How to write a migration to add a column?

namespace WebApiServer.Migrations
{
    using Microsoft.EntityFrameworkCore.Metadata;
    using Microsoft.EntityFrameworkCore.Migrations;
    
    public partial class AddFieldAvatarToUsersTable : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // alter table users alter column add Avatar - varchar(255)
        }
 
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            // alter table users alter column drop Avatar
        }
    }
}

Like in PHP (Laravel)
class AddFieldAvatarToUsersTable extends Migration
{
    /**
     * Run the migration.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function(Blueprint $table){
            $table->string('avatar')->default('default.jpg');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('avatar');
        });
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2018-02-12
@DailyDDose

It is necessary to specify model/db first, but apparently model. Such things are usually not written by hand, but use Add-Migration -Name AddFieldAvatarToUsersTable.
Well, as a matter of fact:
AddColumn("dbo.users", "avatar", c => c.string(nullable: false, defaultValueSql: "default.jpg"));
and
DropColumn("dbo.users", "avatar");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question