I have created code-first app according to this article - Code First to a New Database. Now I am going to change DatabaseGeneratedOption for Blog.BlogId
. I changed my code in next way:
public class Blog
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int BlogId
{
get;set;
}
...
}
And created migration for this code update:
public override void Up()
{
DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs");
DropPrimaryKey("dbo.Blogs");
AlterColumn("dbo.Blogs", "BlogId", c => c.Int(nullable: false, identity: false));
AddPrimaryKey("dbo.Blogs", "BlogId");
AddForeignKey("dbo.Posts", "BlogId", "dbo.Blogs", "BlogId", cascadeDelete: true);
}
According to this I changed code that created blog entity in Main function (added BlogId
there.)
var blog = new Blog
{
Name = name,
BlogId = 110//it could be any other value that isn't represented in column
};
Now when I am trying to run my code I am getting next exception: DbUpdateException with next message - Cannot insert explicit value for identity column in table 'Blogs' when IDENTITY_INSERT is set to OFF.
From other hand when I delete all migrations and create initial migration from updated entity and creating db without identity flag (don't trying to update exist db), my code that create entity with my BlogId
works.
My issue that in real project I have created table and I don't wont to recreate entire table just wont to update key column. How to do it with entity framework migration?