Junior
Junior

Reputation: 11990

How to convert Id attribute from string to int in Identity 2

I am building an application in c# using ASP.NET MVC 5/Entity 6 frameworke with code first approach. I am trying to change the Id attribute in Identity 2 from string to integer.

I followed the documentation which seems to be straight forward.

Then I create the migration using the following command

Add-Migration InitialCreate

The migration file did NOT contain the AspNet tables in it for some reason. But, then I migrated using the following command

Update-Database

The migration was executed with no issues and the seeders run fine.

However, when I run the Application

I get the following error

Exception Details: System.FormatException: Input string was not in a correct format.

The error highlights line 38 below in Startup.Auth.cs File.

Line 36: regenerateIdentityCallback: (manager, user) =>
Line 37: user.GenerateUserIdentityAsync(manager),
Line 38: getUserIdCallback: (id) => (id.GetUserId<int>()))

How can I fix this error?

Upvotes: 2

Views: 1116

Answers (1)

Rosdi Kasim
Rosdi Kasim

Reputation: 25966

You need to delete your cookie. A quick test is to open you app using a different browser (that don't have the cookie yet, maybe use IE or Edge).

This is because when you first browse to the site, a cookie was created (using the string version of the primary key).

When you change your primary key to int, the cookie in your browser is still using the string version, therefore you will get Exception Details: System.FormatException: Input string was not in a correct format. error.

I was stung by this error once, therefore I remember what I had to do to fix it, here is a link for more info: https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys/issues/2

Upvotes: 7

Related Questions