无法在 ASP.NET Core 中更新数据库

Posted

技术标签:

【中文标题】无法在 ASP.NET Core 中更新数据库【英文标题】:Can't update database in ASP.NET Core 【发布时间】:2020-12-02 07:39:48 【问题描述】:

我使用Add-Migrationupdate-database 创建了一个名为USERGOLD 的表,它工作正常,该表是在SQL Server 中创建的,但现在我正在创建另一个表FoodMenu

我创建了一个模型类和dbset,我使用了add-migration,并且在迁移中创建了表,但是当我运行update-database 在SQL Server 中创建表时,它不起作用。我收到一个错误

数据库中已经有一个名为“UserGold”的对象

我不知道为什么 update-database 会接受我之前的迁移。

上下文:

public class RestoContext : IdentityDbContext<RestoUser>

        public RestoContext(DbContextOptions<RestoContext> options)
            : base(options)
        
        

        public DbSet<Menu> Menu  get; set; 
        // public DbSet<Employees> Employee  get; set; 
        public DbSet<Employees> Emp  get; set; 

        public DbSet<Manager> Manager  get; set; 
        public DbSet<GoldMenu> GoldMenu  get; set; 
        public DbSet<UserGold> UserGold  get; set; 
        public DbSet<FoodMenu> FoodMenu  get; set; 

        protected override void OnModelCreating(ModelBuilder builder)
        
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        

我的迁移:

using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace Resto.Migrations

    public partial class AddusergoldToDb : Migration
    
        protected override void Up(MigrationBuilder migrationBuilder)
        
            migrationBuilder.CreateTable(
                name: "UserGold",
                columns: table => new
                
                    userId = table.Column<string>(nullable: false),
                    Usermail = table.Column<string>(nullable: true),
                    CardNumber = table.Column<string>(nullable: true),
                    Validedate = table.Column<DateTime>(nullable: false),
                    Amount = table.Column<float>(nullable: false)
                ,
                constraints: table =>
                
                    table.PrimaryKey("PK_UserGold", x => x.userId);
                );
        

        protected override void Down(MigrationBuilder migrationBuilder)
        
            migrationBuilder.DropTable(
                name: "UserGold");
        
    

控制台应用:

PM> add-migration AddFoodMenuToDatabase

Build started...
Build succeeded.

To undo this action, use Remove-Migration.

PM> update-database

Build started...
Build succeeded.

> fail: Microsoft.EntityFrameworkCore.Database.Command[20102]  
> Failed executing DbCommand (45ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [UserGold] (
          [userId] nvarchar(450) NOT NULL,
          [Usermail] nvarchar(max) NULL,
          [CardNumber] nvarchar(max) NULL,
          [Validedate] datetime2 NOT NULL,
          [Amount] real NOT NULL,
          CONSTRAINT [PK_UserGold] PRIMARY KEY ([userId])
      );
> Failed executing DbCommand (45ms) [Parameters=[], CommandType='Text', CommandTimeout='30']  
CREATE TABLE [UserGold] (
    [userId] nvarchar(450) NOT NULL,
    [Usermail] nvarchar(max) NULL,
    [CardNumber] nvarchar(max) NULL,
    [Validedate] datetime2 NOT NULL,
    [Amount] real NOT NULL,
    CONSTRAINT [PK_UserGold] PRIMARY KEY ([userId])
);  
> Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'UserGold' in the database.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
   at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:64024c74-897d-421e-bb48-ef96cb315f44
Error Number:2714,State:6,Class:16

数据库中已经有一个名为“UserGold”的对象

【问题讨论】:

检查表 _migrations_history 并比较添加了哪些迁移。 如何查看? 在任何数据库查看器或命令行中可视化。检查表中的记录。 您之前是否手动删除过迁移文件?执行命令add-migration AddFoodMenuToDatabase后,您可以向我们展示迁移文件AddFoodMenuToDatabase 【参考方案1】:

迁移过程中似乎有问题,在“包管理器控制台”中运行 add-migration 命令。

你的问题可能是重复的here

【讨论】:

以上是关于无法在 ASP.NET Core 中更新数据库的主要内容,如果未能解决你的问题,请参考以下文章

在 asp.net core 中插入/更新记录时出错

更新到 ASP.NET Core 2 后无法获取配置部分

解决ASP.NET Core部署到IIS,更新项目"另一个程序正在使用此文件,进程无法访问"

在 ASP .Net Core MVC 中启动时执行数据库更新

解决ASP.NET Core部署到IIS,更新项目"另一个程序正在使用此文件,进程无法访问"...

解决ASP.NET Core部署到IIS,更新项目"另一个程序正在使用此文件,进程无法访问"...