【问题标题】:EF - Default value for new column with automatic migrationEF - 具有自动迁移的新列的默认值
【发布时间】:2015-01-07 18:32:54
【问题描述】:

我首先使用 EF 代码和自动迁移。我想在我的模型中添加一个新列 - 一个布尔列来表示“活动”(真)或“非活动”(假)。如何添加此列并为数据库中已有的行设置默认值(“true”) - 自动迁移?

【问题讨论】:

    标签: c# entity-framework ef-code-first entity-framework-migrations automatic-migration


    【解决方案1】:

    Tamar,您需要设置默认值,请参见下一个示例:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-04
    • 2016-09-08
    • 2012-09-03
    • 2021-09-01
    • 2015-08-12
    • 2013-05-08
    • 2016-08-28
    • 2011-11-08
    相关资源
    最近更新 更多