-1

I'm trying to create a MVC5 webapp, Asp.Net.Identity.Core (2.2.3), using DevArt MySQL drivers along with DevArt MySql Identity (8.21.2066.0) and EF 6

I'm having a concurrency issue when trying to add a user to a role. (Specifically this part of the code: var result1 = UserManager.AddToRole(user.Id, "Admin");

The Trace Stack follows:

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException
  HResult=0x80131501
  Message=Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
  Source=mscorlib
  StackTrace:
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<SaveChanges>d__61.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<UpdateAsync>d__40.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.UserManager`2.<UpdateAsync>d__74.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.UserManager`2.<AddToRoleAsync>d__105.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func`1 func)
   at DEV_Art_Test_2.Startup.createRolesandUsers() in E:\REPOS\Devart\NET Test 2\DEV Art Test 2\Startup.cs:line 50
   at DEV_Art_Test_2.Startup.Configuration(IAppBuilder app) in E:\REPOS\Devart\NET Test 2\DEV Art Test 2\Startup.cs:line 15

I'm running the following my startup to seed the DB:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        createRolesandUsers();
    }


    // In this method we will create default User roles and Admin user for login    
    private void createRolesandUsers()
    {
        ApplicationDbContext context = new ApplicationDbContext();

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));


        // In Startup iam creating first Admin Role and creating a default Admin User     
        if (!roleManager.RoleExists("Admin"))
        {

            // first we create Admin rool    
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Admin";
            roleManager.Create(role);

            //Here we create a Admin super user who will maintain the website                   

            var user = new ApplicationUser();
            user.UserName = "bob";
            user.Email = "test@test.com";

            string userPWD = "Test1234";
            var chkUser = UserManager.Create(user, userPWD);

            //context.Entry(chkUser).State = System.Data.Entity.EntityState.Modified;
            //context.SaveChanges();


            //Add default User to Role Admin    
            if (chkUser.Succeeded)
            {
                var result1 = UserManager.AddToRole(user.Id, "Admin");

            }
        }





        // creating Creating Manager role     
        if (!roleManager.RoleExists("Manager"))
        {
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Manager";
            roleManager.Create(role);

        }

        // creating Creating Employee role     
        if (!roleManager.RoleExists("Employee"))
        {
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Employee";
            roleManager.Create(role);

        }

    }
}

As you see in the code, I did try to set the entity state to modified to see if it would save and got the same result. Any assistance on what I'm doing wrong would be appreciated.

Bob Randolph
  • 43
  • 1
  • 7
  • In which line is the exception thrown? Here? `var chkUser = UserManager.Create(user, userPWD);` – Sebastian Siemens Jun 16 '22 at 21:51
  • No. I've updated the OP. This is where I'm having the issue: var result1 = UserManager.AddToRole(user.Id, "Admin"); – Bob Randolph Jun 17 '22 at 14:06
  • MVC5 is ancient and obsolete. Why aren't you using ASP.NET Core? – Ian Kemp Jun 17 '22 at 15:05
  • Going with what I know at this point. Still using in in my corporate job as well, so just keeping everything on the same level. – Bob Randolph Jun 17 '22 at 15:42
  • 1
    Please specify "Found Rows=true;" in your connection string. This parameter makes the provider return the number of rows matched by the WHERE condition of the UPDATE statement instead of the rows actually changed. – Devart Oct 07 '22 at 10:09

1 Answers1

0

Why don't you use DependencyInjection to get the required services for userManager and roleManager. ApplicationDbContext is not required.:

  private void createRolesandUsers(app)
  {
      var userManager = app.ApplicationServices.GetRequiredService<UserManager<ApplicationUser>>();
      var roleManager = app.ApplicationServices.GetRequiredService<RoleManager<IdentityRole>>();
      // Creating default user and roles logic
  }

Does adding a user to a role, take the user Id, or the ApplicationUser object?

await userManager.AddToRoleAsync(user, "Admin");