Reputation: 13
I added a foreign key to default Identity ApplicationUser class. The problem is: When I create a new user, the ForeignKey parameter on database remains NULL.
My ApplicationUser class.
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);
}
}
Context
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("someConnectionString", throwIfV1Schema: false)
{
}
public DbSet<Sala> Salas { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
In my AccountController I try to add a new user
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);
}
}
Upvotes: 1
Views: 1238
Reputation: 11347
Use a property instead of a field for SalaId
public class ApplicationUser : IdentityUser
{
//Foreing Key
public Guid SalaId { get; set; }
}
Upvotes: 3