实体框架代码优先迁移始终尝试创建新数据库
本文关键字:创建 数据库 代码 框架 迁移 实体 | 更新日期: 2023-09-27 18:32:50
我在视频上做每一步 https://www.youtube.com/watch?v=i7SDd5JcjN4
- PM>启用迁移
- 更改我的实体模型(添加一些属性)
- 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