Entity Framework migration error

2

I added a new table to my existing SQL Server database. I am using its generated id as the key. I ran dotnet ef migration add NewTable, which ran without errors. I reviewed the migration file and this is what was added for my new table:

migrationBuilder.CreateTable(
                name: "InboxNotifications",
                columns: table => new
                {
                    Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
                    Created = table.Column<DateTime>(type: "datetime2", nullable: false),
                    CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    DataId = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    EventIdent = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Message = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Status = table.Column<int>(type: "int", nullable: false),
                    TeamIdent = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Title = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Type = table.Column<int>(type: "int", nullable: false),
                    UserId = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_InboxNotifications", x => x.Id);
                });

Now, when I run dotnet ef database update I get this error:

fail: Microsoft.EntityFrameworkCore.Database.Command[200102]
Failed executing DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [ApplicationUserToken] DROP CONSTRAINT [FK_ApplicationUserToken_AspNetUsers_UserId];
System.Data.SqlClient.SqlException (0x80131904): Cannot find the object "ApplicationUserToken" because it does not exist or you do not have permissions.

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary
2 parameterValues)

I'm not quite sure what that means as I did not change anything else within my db context file. I only added the new model.

EDIT:

So I have this function called in Configure() inside startup.cs:

`

public virtual void EnsureDatabaseCreated(TennisFolderContext dbContext,
                              UserManager<ApplicationUser> userManager,
                              RoleManager<ApplicationRole> roleManager,
                              bool createData)
        {

            // run Migrations
            DbInitializer.Initialize(dbContext, userManager, roleManager, createData).Wait();
        }

`

According to https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/

Moving it to program.cs did not fix it. Can't seem to figure out what is going on.

c#
asp.net
sql-server
entity-framework
asked on Stack Overflow Apr 9, 2018 by user6728767 • edited Apr 9, 2018 by user6728767

3 Answers

2

Given code does not indicate any change in ApplicationUserToken. So make sure than you are connected to same DB(verify your context file). Check if you have called initialized the your DBContext.

answered on Stack Overflow Apr 9, 2018 by Anis ur Rehman
0

I found the solution for this issue, just create new database & execute command "add-migration migrationame" and then update-database from package manager console.

answered on Stack Overflow Jun 15, 2019 by Delendra Patle
0

The problem is that you have a migration that for some reason is referencing a constraint that has either not been created or deleted.

To solve this

  1. Check your migration history table on your database (_EFMigrationsHistory) to know the last successful migration.
  2. Go to the migrations folder in your solution and check for the migration added after the last successful migration.
  3. The error is most like from a statement that is trying to drop the FK_ApplicationUserToken_AspNetUsers_UserId, usually written like:

    migrationBuilder.DropForeignKey( name: "FK_ApplicationUserToken_AspNetUsers_UserId", table: "Your table")

  4. You can either comment this statement or delete it

  5. Try to update your database again
answered on Stack Overflow May 17, 2020 by Ose • edited May 23, 2020 by Ose

User contributions licensed under CC BY-SA 3.0