Get User Entity ID

Asked

Viewed 129 times

0

I’m trying to get the user id and save in the table, here’s how I referenced in the Foreignkey table:

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

And here’s how I’m trying to play for the table:

public async Task<IActionResult> OnPost()
    {
        if (ModelState.IsValid)
        {
            var CR = _context.ContasReceber.Find(ContasReceberVM.ContasReceber.Id);
            CR.Quitado = true;
            CR.ValorPago = Convert.ToDecimal(ContasReceberVM.ContasReceber.ValorPago.ToString().Replace(",","."));
            CR.FormaPagamento = ContasReceberVM.ContasReceber.FormaPagamento;
            CR.DataPagamento = DateTime.Now;
            ApplicationUser a = new ApplicationUser();
            CR.FuncionarioId = a.Id;
            await _context.SaveChangesAsync();
            Message = "Pagamento Realizado com Sucesso!";

            return RedirectToPage("Index");
        }
    }

However this way, it does not take the correct ID, it takes an ID that does not exist, ai returns me the following error.

The UPDATE statement conflicted with the FOREIGN KEY constraint "Fk_contasreceber_aspnetusers_funcionarioid". The conflict occurred in the database "Cronoparque", table "dbo.Aspnetusers", column 'Id'. The instruction has been completed.

It returns this error because the ID does not match the ID registered in the Aspnetusers table.

  • The code of _context.ContasReceber is in 1 controller? could add the whole action in question?

  • I edited the question, it is in the controller of the Edit page, created by the Razor page.

  • You can’t get the user ID like this: User.Identity.Getuserid(); ?

  • @Gustavosantos no, it returns me this error, how much I try this way: "Iidentity" does not contain a definition for "Getuserid" and could not find any extension method "Getuserid" that accepts a first argument of type "Iidentity"

  • You need to import Microsoft.AspNet.Identity.Identityextensions to use this method

  • Already use, using Microsoft.AspNetCore.Identity;

  • 1

    You’re giving a new in the ApplicationUser this will generate a new ID, you need to retrieve the current user, as answered in the question:

  • It seems to me you need to do CR.ApplicationUser = a; instead of CR.FuncionarioId = a.Id;. When you create a new ApplicationUser Id does not exist. It will only exist after SaveChanges.

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.