Entity framework 代码优先迁移总是尝试创建新数据库

Entity framework code first migration always tries to create new database

那个视频的每一步我都做 https://www.youtube.com/watch?v=i7SDd5JcjN4

  1. PM> 启用迁移
  2. 更改我的实体模型(添加一些属性)
  3. PM> 添加迁移迁移名称

还有VS重新生成创建数据库的代码。但我只需要添加 1 属性.

如果您需要代码: 1.迁移生成:

public partial class alter2 : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Articles",
            c => new
                {
                    Id = c.Int(nullable: false),
                    Content = c.String(),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.Chapters", t => t.Id)
            .Index(t => t.Id);

        CreateTable(
            "dbo.Chapters",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Title = c.String(),
                    CreationDate = c.DateTime(nullable: false),
                    Level = c.Int(nullable: false),
                    Url = c.String(),
                    Intro = c.String(),
                    Outro = c.String(),
                    MyProperty = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id);

    }

    public override void Down()
    {
        DropForeignKey("dbo.Articles", "Id", "dbo.Chapters");
        DropIndex("dbo.Articles", new[] { "Id" });
        DropTable("dbo.Chapters");
        DropTable("dbo.Articles");
    }
}

我的实体:

public class Article {

    public int Id {
        get;
        set;
    }

    public string Content {
        get;
        set;
    }

    public virtual Chapter Chapter {
        get;
        set;
    }

}

public class Chapter {

    [ForeignKey ("Article")]
    public int Id {
        get;
        set;
    }

    public string Title {
        get;
        set;
    }

    public DateTime CreationDate {
        get;
        set;
    }

    public int Level {
        get;
        set;
    }

    public string Url {
        get;
        set;
    }

    public virtual Article Article {
        get;
        set;
    }

    public string Intro {
        get;
        set;
    }

    public string Outro {
        get;
        set;
    }

    public int MyProperty {
        get;
        set;
    }

}

EF 上下文:

public class EFContext : DbContext {

    public EFContext () : base ("name=EFContext") {}

    public virtual DbSet<Chapter> Chapters {
        get;
        set;
    }

    public virtual DbSet<Article> Articles {
        get;
        set;
    }

    protected override void OnModelCreating (DbModelBuilder modelBuilder) {

        modelBuilder.Entity<Article> ()
                    .HasRequired (a => a.Chapter).WithOptional (a => a.Article);

    }

}

您需要初始基线迁移。 EF 将始终将新迁移与之前的迁移进行比较,因此如果您之前没有任何迁移,它将添加代码来创建数据库中已有的对象。因此,在启用迁移之后但在更改模型之前执行此操作:

Add-Migration InitialCreate –IgnoreChanges
Update-Database

现在您的下一次迁移将是增量的。

https://msdn.microsoft.com/en-us/data/dn579398.aspx#option1