I'm trying to setup a many to many relationship in EF 6.1 from the User entity (ApplicationUser) in ASP.NET Identity to a custom entity (Group). I'm using Code First and Migrations with the stock standard MVC sample app with ASP.Net Identity. Running Update-Database seems to work nicely as I end up with all the AspNet* tables plus my entity and a linking table:
Groups
GroupAspNetUsers
My ApplicationUser declaration has a collection of Group, and likewise my Group has a collection of ApplicationUser:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Group> Groups { get; set; }
I can create users and groups, but for the life of me I can't work out how to link them. I would have expected something like this to work:
Group group = Context.Groups.Single(g => g.Id == 1);
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// link this user to a group
group.ApplicationUsers.Add(user);
Context.SaveChanges();
However when I run the code above, I get a DbEntityValidationException stating the user name is already taken.
I've tried loading 2 custom entities and linking them in this way, which inserts a record into the linking table no problem.
So there is something I don't follow about how ApplicationUser is different.
My custom entities and the ASP.Net Identity entities should be using the same DB context as all my controllers inherit from a base controller.
UPDATE:
I've also tried approaching this from the other way around (add a group to a user), without any luck:
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// attempting to add group to a user
user.Groups.Add(group);
Context.SaveChanges();
This code runs without throwing an error, however it doesn't add a record to my GroupAspNetUsers table though.
My next step is to try creating a separate entity (eg. UserInfo) which has a 1 to 1 mapping with ApplicationUser. Then I should be able to setup a many to many from UserInfo to Group.
SOLUTION
The double insert problem stems from the UserManager.CreateAsync call, which will create the user on a different thread. The current thread, being unaware of this, then tries to insert the user again.
Changing the method to UserMannager.Create solved the problem, however as @Horizon_Net pointed out there are other issues with mixing identity and context methods (which I ran into).
The solution was to create the user, then redirect off to another controller to link the user to a group. This worked without a hitch.