简体   繁体   English

C#实体框架迁移,使ID自动递增

[英]C# Entity Framework migration, Make ID auto-increment

I have a table that is used in an Entity Framework context that was generated using a database-first approach. 我有一个表,该表在使用数据库优先方法生成的Entity Framework上下文中使用。

I made a mistake, and the ID for one table is not auto-incrementing. 我犯了一个错误,并且一个表的ID不会自动递增。 I am unsure as to what the best approach to solve this is. 我不确定解决此问题的最佳方法是什么。

Should I drop the table, and generate it again? 我应该放下表格,然后再次生成表格吗?

Can I make a migration to make this ID auto-increment? 我可以进行迁移以使该ID自动递增吗?

Is there another option? 还有其他选择吗?

Thanks in advance 提前致谢

If the table was created using Database first you can alter it in SSMS if you use this? 如果该表是首先使用数据库创建的,那么您可以在SSMS中对其进行更改吗? Then open up the .edmx file in Visual Studio, right click the background somewhere and select update model from database. 然后在Visual Studio中打开.edmx文件,右键单击某处的背景,然后从数据库中选择更新模型。 Go through the options you need (probably just the refresh table), once you have done this you will need to save the .edmx file. 浏览所需的选项(可能只是刷新表),完成此操作后,您将需要保存.edmx文件。

You can enable code first migrations and update your database: 您可以启用代码优先迁移并更新数据库:

  1. Add [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute to your ID column [DatabaseGenerated(DatabaseGeneratedOption.Identity)]属性添加到您的ID列

  2. Run this command in Package Manager Console to enable migrations: 在程序包管理器控制台中运行以下命令以启用迁移:

     Enable-Migrations 
  3. Update database using these commands : 使用以下命令更新数据库:

     Add-Migration Update-Database 

    (First run Add-Migration , and then run Update-Database command) (首先运行Add-Migration ,然后运行Update-Database命令)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM