与ASP.NET身份表和自定义表有多对多的关系

时间:2016-06-04 08:44:01

标签: c# asp.net entity-framework

我在ASP.NET Identity中的AplicationUser表与自定义表(Teams)之间存在多对多的关系。我需要插入一个用户并将其链接到数据库中已存在的团队,它还必须在ApplicationUserTeams表中插入一条记录。我正在做这样的事情,但它在Team表中创建了一条新记录。我无法访问UserManager上下文以附加团队。我很感激你的想法吗?

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();
    }

这个型号: enter image description here

1 个答案:

答案 0 :(得分:0)

当实体被添加到上下文时,所有粘附的实体在尚未附加到上下文时也被标记为Added。这是一个EF功能,让开发人员感到困惑。

一旦你知道了,如果你有权访问上下文,那么很清楚该做什么:

var team = new Team();

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

但我不知道你是如何实例化UserManager的。您可能无法访问控制器代码中的上下文。如果是这样,最好将联结表合并到类模型中,这将使裸类模型看起来像这样:

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; }
}

现在您只需将ApplicationUserTeam对象添加到ApplicationUser.ApplicationUserTeams