EF - Default value for new column with automatic migration

我的梦境 提交于 2020-01-14 08:03:46

问题


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?


回答1:


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"); 
        } 
    } 
} 


来源:https://stackoverflow.com/questions/26861013/ef-default-value-for-new-column-with-automatic-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!