I just upgraded my MVC 5 application (was previously MVC 3 with SimpleMembership
) to ASP.NET Identity 2.0 and I can work with existing users, but when I execute the following to create a new user:
var user = new ApplicationUser();
//user.Id = db.Users.Max(u => u.Id) + 1; //does not help
user.UserName = model.UserName;
user.Email = model.EMailAddress;
var result = await UserManager.CreateAsync(user, model.Password);
I get the following:
System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'MyDB.dbo.AspNetUsers'; column does not allow nulls. INSERT fails. The statement has been terminated.
Does anyone have an idea why this is happening?
This is my UserManager
:
var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<MyDbContext>()));
manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
manager.EmailService = new EmailService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
}
I use int
keys for the users and roles, but I had the default string
-keys before and there the Id
was also not filled and I got a similar error.
I found the problem:
Because I changed the key from string
to int
the following migration was created:
AlterColumn("dbo.AspNetUsers", "Id", c => c.Int(nullable: false, identity: true));
There it correctly generated identity: true
, BUT MSSQL can't convert an existing column to an identity column => the column became a "normal INT
column".
Identity must then asume that the column is an identity column and inserts null
as the key and expects the DB to generate the id => exception.
The solution was to revert back to my SimpleMembership
DB from an old backup and directly convert it to ASP.NET Identity
using the int
-key when creating the AspNetUsers
-table.
P.S.: But I still don't know why I had similar problems with string
-keys, but I like the int
-keys better anyhow...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With