Getting 'An item with the same key has already been added' error when clicking on the 'Details' link


I downloaded the 24433 build this morning. I loaded the Trunk file in Visual Studio. The solution built with no error. I run the site and the initial User Admin page come up fine. Pageing works. Whne I click on the user name to go to the Details page I get the following YSOD:
An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: An item with the same key has already been added.
Source Error:
Line 79: var user = _userService.Get(id);
Line 80: var userRoles = _rolesService.FindByUser(user);
Line 81: return View(new DetailsViewModel
Line 82: {
Line 83: DisplayName = user.UserName,
Source File: C:\mcb\work\Apps\MVC\Membership\MVC_membership\Build_24433\trunk\SampleWebsite\Controllers\UserAdministrationController.cs Line: 81
Let me know if you need any additional information.
Closed Aug 9, 2009 at 5:07 PM by TroyGoode
Glad to see we found the root of the problem. In my testing I was unable to duplicate your scenario as the default ASPNETDB has an index on the RoleName column preventing duplicates. I assume you're using a custom RoleProvider or have in some other way customized the role database and lost this constraint.I've committed a change to the trunk that checks for the existence of duplicates and throws a meaningful error message so that hopefully this will be clearer to anyone encountering this problem in the future.


TroyGoode wrote Aug 7, 2009 at 5:50 PM

Interesting. It appears to be this line that is throwing it:

*_rolesService.FindAll().ToDictionary(role=> role, role=> userRoles.Contains(role))*

The purpose of this line is to turn a list of all the roles in the system into a dictionary that contains the role and a boolean denoting whether or not the selected user is in that role. The error message "An item with the same key has already been added." suggests that a duplicate role exists. Would you mind posting what roles are listed on the User Administration's Index page?

If the problem is indeed what I suspect, changed FindAll().ToDictionary to FindAll().Distinct().ToDictionary should fix your problem - but I'd love to know how the list of roles is getting a duplicate in there.

wrote Aug 7, 2009 at 5:50 PM

wrote Aug 7, 2009 at 5:51 PM

putrtek wrote Aug 7, 2009 at 7:12 PM

Good Catch Troy that was it. There was in fact a duplicate RoleName in the aspnet_Roles table. Differant RoleID's but the same RoleName... Deleting the duplicate role resolved the issue Everything works fine. I'm able to get to the details screen now and update and save user info. Thanks for your assistance.


wrote Aug 9, 2009 at 5:05 PM

wrote Aug 9, 2009 at 5:07 PM

wrote Feb 14, 2013 at 7:12 PM

wrote May 16, 2013 at 9:02 AM