标识用户上的外键

本文关键字:用户 标识 | 更新日期: 2023-09-27 18:32:41

我在默认的 Identity 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();
    }  
}

在我的帐户控制器中,我尝试添加新用户

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

标识用户上的外键

对 SalaId 使用属性而不是字段

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