6

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://learn.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.

2
  • it seems like FK_ApplicationUserToken_AspNetUsers_UserId key could not be found in your DB. The exception is very clear... Commented Apr 9, 2018 at 18:07
  • Where have you defined ApplicationUserToken. The code shared above does not specify ApplicationUserToken. Check you code for the errors. Also check if you db is using any other keys which you have not defined. Commented Apr 9, 2018 at 18:15

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So it looks like the first line in the migration constructor is DropForeignKey of the ApplicationUserToken. If its the first line its prob being hit first, which would probably mean that my db isn't being hit right? I recently did a migration from .NET 1.1.4 to .NET 2.0.0 so I'll have to review my changes.
it might be a problem, as System.Data.SqlClient.SqlException (0x80131904) shows an access error.
Is there anything else you'd recommend me try? I'm completely stumped. I'm taking over this project from another dev that is no longer here so this is all new to me.
1

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

1 Comment

I agree. Also another option; It may revert to the migration version previous to the error. And then you can continue by adding the new migration. I think this is the healthiest way to work.
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.

1 Comment

I don't think that was the user's problem. He had a problem with the connection. Recreating the Db wouldn't help much.
0

for this first make sure that you have wrote the data file correct. If that is correct then run the migration files in package manager console i.e

Command : Add-Migration Migration_name (if you have the migrations folder in your solution explorer then first you delete that folder and run this command)

after this run another command Command : Update-Database (It Will help in syncing the code with the sql server and creates a tables in the database)

After this open your TERMINAL then run following commands

first check wethere you are in your project only means you should see the folders of projects when you run the "dir" command (that can be seen by executing following commands)

command : dir if you are not in your project directory then switch to your project that is command : cd projectname then command : dotnet run seeddata

1 Comment

Welcome to SO! Please do not link to external resources for a solution, except additional information on wiki pages and documentation. Refer to How do I write a good answer guidline to improve your contribution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.