身份用户的外键

时间:2016-02-01 13:11:40

标签: c# asp.net-mvc entity-framework identity

我在默认的Identity ApplicationUser类中添加了一个外键。 问题是:当我创建新用户时,数据库上的ForeignKey参数保持为NULL。

我的ApplicationUser类。

public class ApplicationUser : IdentityUser
{
//Foreing Key
    public Guid SalaId;
    public virtual Sala Sala { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

    }
}

上下文

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("someConnectionString", throwIfV1Schema: false)
    {         
    }

    public DbSet<Sala> Salas { get; set; }
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }  
}

在我的AccountController中,我尝试添加一个新用户

private ApplicationDbContext db = new ApplicationDbContext();

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
//here I find the 'Sala' with the 'numero' parameter from View 
            var x = db.Salas. Where(y => y.Numero == model.Sala).FirstOrDefault();
            var user = new ApplicationUser { UserName = model.Username,
                                Email = model.Email, SalaId = x.Id };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }
    }

1 个答案:

答案 0 :(得分:1)

使用属性而不是SalaId的字段

 public class ApplicationUser : IdentityUser
 {
     //Foreing Key
     public Guid SalaId { get; set; }
 }