Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF - Default value for new column with automatic migration

I use EF code first and automatic migrations. I want to add a new column to my model - a boolean column to present "active" (true) or "inactive" (false). How can I add this column and set a default value ("true") for the rows that already in the DB - with automatic migrations?

like image 585
TamarG Avatar asked Nov 11 '14 08:11

TamarG


People also ask

How do I set the default value in Entity Framework?

In the DbContext OnModelCreating you add the default value. The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type.

What is ADD migration initial?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.

How does EF migration work?

EF Core compares the current model against a snapshot of the old model to determine the differences, and generates migration source files; the files can be tracked in your project's source control like any other source file. Once a new migration has been generated, it can be applied to a database in various ways.


1 Answers

Tamar, you need set default value, see next sample:

namespace MigrationsDemo.Migrations 
{ 
    using System; 
    using System.Data.Entity.Migrations; 

    public partial class AddPostClass : DbMigration 
    { 
        public override void Up() 
        { 
            CreateTable( 
                "dbo.Posts", 
                c => new 
                    { 
                        PostId = c.Int(nullable: false, identity: true), 
                        Title = c.String(maxLength: 200), 
                        Content = c.String(), 
                        BlogId = c.Int(nullable: false), 
                    }) 
                .PrimaryKey(t => t.PostId) 
                .ForeignKey("dbo.Blogs", t => t.BlogId, cascadeDelete: true) 
                .Index(t => t.BlogId) 
                .Index(p => p.Title, unique: true); 

            AddColumn("dbo.Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3)); 
        } 

        public override void Down() 
        { 
            DropIndex("dbo.Posts", new[] { "Title" }); 
            DropIndex("dbo.Posts", new[] { "BlogId" }); 
            DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs"); 
            DropColumn("dbo.Blogs", "Rating"); 
            DropTable("dbo.Posts"); 
        } 
    } 
} 
like image 63
Dmitry Andreev Avatar answered Sep 27 '22 18:09

Dmitry Andreev