本文介绍了EF-具有自动迁移功能的新列的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用EF代码并进行自动迁移.我想在模型中添加一个新列-一个布尔列以显示活动"(true)或非活动"(false).如何添加此列并为数据库中已存在的行设置默认值("true")-自动迁移?

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?

推荐答案

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

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

这篇关于EF-具有自动迁移功能的新列的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 08:43