我在该视频https://www.youtube.com/watch?v=i7SDd5JcjN4
上执行了每一步然后VS重新生成创建数据库的代码。但我只需要添加一个属性。
如果您需要代码: 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);
}
}
答案 0 :(得分:5)
您需要初始基线迁移。 EF将始终将新迁移与之前的迁移进行比较,因此如果您之前没有任何内容,则可以添加代码来创建数据库中已有的对象。因此,在启用迁移之后,但在进行模型更改之前,请执行此操作:
Add-Migration InitialCreate –IgnoreChanges
Update-Database
现在您的下一次迁移将是增量式的。