How to relate a model to ApplicationUser

0

I can not find how to relate my client model with ApplicationUser, I want a one-to-one relationship. Someone knows where the error is:

    public class ApplicationUser : IdentityUser
{
    public virtual Cliente Cliente { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Tenga en cuenta que el valor de authenticationType debe coincidir con el definido en CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Agregar aquí notificaciones personalizadas de usuario
        return userIdentity;
    }
}

public class Cliente
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Cedula { get; set; }

    public string Nombre { get; set; }

    [ForeignKey("ApplicationUser")]
    public string UserId { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }
}

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

    public DbSet<Cliente> Clientes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>().HasOptional(c => c.Cliente)
            .WithRequired(c => c.ApplicationUser);
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}


    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                ApplicationDbContext db = new ApplicationDbContext();
                Cliente cliente = new Cliente { Cedula = "xxxxx", Nombre = "John", UserId = user.Id, ApplicationUser = user };
                db.Clientes.Add(cliente);
                db.SaveChanges();
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                // Enviar correo electrónico con este vínculo
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>");

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

        // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
        return View(model);
    }

This code is a test but it is basically how I intend to do it, but it does not work for me. thanks in advance.

    
asked by Johander 20.06.2017 в 22:50
source

1 answer

0

If you want to relate the ApplicationUser with the Cliente you should do it by means of the property that you define

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

Cliente cliente = new Cliente { Cedula = "xxxxx", Nombre = "John", UserId = user.Id, ApplicationUser = user };
user.Cliente = cliente;

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

if (result.Succeeded)
{
    //resto codigo

It is important to highlight the line

user.Cliente = cliente;

when you create the user you assign the client to be registered all together, you do not perform it in two different operations

    
answered by 21.06.2017 в 19:06