我正在使用ef code first迁移创建一个类似c/.net 4.5框架的博客。
直到把第三段感情加入我的主班,一切都进展顺利。
我有一个“故事”类(有点像博客的“文章”),其中作者是登录的用户(设置在控制器中)、标题、一些内容、创建日期以及类型和类型的故事。
public class Story
{
public int Id { get; set; }
public string AuthorId { get; set; }
public virtual ApplicationUser Author { get; set; }
[Required]
[StringLength(50)]
public string Title { get; set; }
[Required]
[MinLength(100), MaxLength(5000)]
public string Content { get; set; }
[Required]
public int GenreId { get; set; }
public Genre Genre { get; set; }
[Required]
public int StoryTypeId { get; set; }
public StoryType StoryType { get; set; }
public DateTime CreatedAt { get; set; }
}
我添加了故事类型作为故事的属性。StoryType链接到StoryType模型:
public class StoryType
{
public int Id { get; set; }
public string Name { get; set; }
}
我确保将dbset添加到应用程序db上下文中:
public DbSet<Genre> Genres { get; set; }
public DbSet<Story> Stories { get; set; }
public DbSet<StoryType> StoryTypes { get; set; }
我基本上遵循了我过去创建故事和流派之间关系的相同步骤(这很好)。在我开始构建StoryType控制器之前,我进入包控制台并运行:
add-migration
返回:
public partial class CreateTypeTable : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.StoryTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
AddColumn("dbo.Stories", "StoryTypeId", c => c.Int(nullable: false));
CreateIndex("dbo.Stories", "StoryTypeId");
AddForeignKey("dbo.Stories", "StoryTypeId", "dbo.StoryTypes", "Id", cascadeDelete: true);
}
public override void Down()
{
DropForeignKey("dbo.Stories", "StoryTypeId", "dbo.StoryTypes");
DropIndex("dbo.Stories", new[] { "StoryTypeId" });
DropColumn("dbo.Stories", "StoryTypeId");
DropTable("dbo.StoryTypes");
}
}
看了一眼,我没看到问题,就跑:
update-database
在程序包控制台中。
返回:
Error Number:547,State:0,Class:16
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Stories_dbo.StoryTypes_StoryTypeId". The conflict occurred in database "aspnet-HiRatik.Stories-20180724043630", table "dbo.StoryTypes", column 'Id'.
我不知道这里出了什么问题。我对体裁关系也做了同样的处理,它起作用了。我看不出两者有什么不同。