简体   繁体   中英

Many to many relationship with ASP.NET Identity Table and Custom Table

I have got a many to many relationship between AplicationUser table from ASP.NET Identity to a custom table (Teams). I need to insert a user and link it to a team that already exists in the data base, it must insert a record in the ApplicationUserTeams table as well. I am doing something like this but it creates a new record in Team table. I do not have access to the UserManager Context in order to attach a team. I would appreciate any idea?

public async Task<IHttpActionResult> RegisterUser(RegisterRecordBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        var Team = new Team();
        Team.TeamId = model.teamId;
        user.Teams.Add(team);

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

This the model: 在此输入图像描述

When an entity is added to a context, all adhering entities are marked as Added too when they're not yet attached to the context . This is an EF feature that keeps confounding developers.

Once you know it, it's clear what to do, if you have access to the context:

var team = new Team();

team.TeamId = model.teamId;
user.Teams.Add(team);
context.Teams.Attach(team);
...

But I don't know how you instantiated your UserManager . You may not have access to its context in your controller code. If so, it's better to incorporate the junction table in the class model, which would make the bare class model look like this:

class ApplicationUserTeam
{
    [Key, Column(Order = 1)]
    public int ApplicationUserID { get; set; }
    [Key, Column(Order = 2)]
    public int TeamID { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
    public Team Team { get; set; }
}

class ApplicationUser
{
    public ApplicationUser()
    {
        ApplicationUserTeams = new HashSet<ApplicationUserTeam>();
    }
    public int ID { get; set; }
    public ICollection<ApplicationUserTeam> ApplicationUserTeams { get; set; }
}

class Team
{
    public Team()
    {
        ApplicationUserTeams = new HashSet<ApplicationUserTeam>();
    }
    public int ID { get; set; }
    public ICollection<ApplicationUserTeam> ApplicationUserTeams { get; set; }
}

Now you can simply add an ApplicationUserTeam object to ApplicationUser.ApplicationUserTeams .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM