gpt4 book ai didi

c# - 在 Entity-Framework 中使用更新的 DatabaseGeneratedOption 迁移实体

转载 作者:太空狗 更新时间:2023-10-29 23:06:43 24 4
gpt4 key购买 nike

我已经根据这篇文章创建了代码优先应用程序 - Code First to a New Database .现在我要为 Blog.BlogId 更改 DatabaseGeneratedOption。我用下一种方式更改了我的代码:

public class Blog
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int BlogId
{
get;set;
}
...
}

并为此代码更新创建迁移:

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);
}

据此,我更改了在 Main 函数中创建博客实体的代码(在那里添加了 BlogId。)

var blog = new Blog
{
Name = name,
BlogId = 110//it could be any other value that isn't represented in column
};

现在,当我尝试运行我的代码时,出现下一个异常:DbUpdateException 和下一条消息 - 当 IDENTITY_INSERT 设置为时,无法在表“博客”中为标识列插入显式值关闭。

另一方面,当我删除所有迁移并从更新的实体创建初始迁移并创建没有标识标志的数据库(不要尝试更新现有数据库)时,我的代码使用我的 BlogId 创建实体有效。

我的问题是在实际项目中我已经创建了表并且我不会重新创建整个表只是不会更新键列。 Entity Framework 迁移怎么做?

最佳答案

您正试图从列中删除 IDENTITY 属性,不幸的是,这通常不是微不足道的(至少对于 SQL Server,我认为这是不可能的)。

有关一些解释,请参阅:


最后几个链接还提供了一些关于如何自定义迁移以删除 IDENTITY 列并仍然保留数据的想法。例如,从最后一个链接:

The steps for changing the identity setting on a column in SQL Server are:

  1. Drop all foreign key constraints that point to the primary key we are changing
  2. Drop the primary key constraint
  3. Rename the existing column (so that we can re-create the foreign key relationships later)
  4. Add the new primary key column with the new identity setting
  5. Update existing data so that previous foreign key relationships remain
  6. If the new column is an identity column, we need to update all foreign key columns with the new values
  7. If the new column doesn’t have identity on, we can copy the old values from the previous identity column
  8. Drop old primary key column
  9. Add primary key constraint
  10. Add back foreign key constraints

http://romiller.com/2013/04/30/ef6-switching-identity-onoff-with-a-custom-migration-operation/

关于c# - 在 Entity-Framework 中使用更新的 DatabaseGeneratedOption 迁移实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com