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?– Barbetta
I edited the question, it is in the controller of the Edit page, created by the Razor page.
– Mariana
You can’t get the user ID like this: User.Identity.Getuserid(); ?
– Gustavo Santos
@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"
– Mariana
You need to import Microsoft.AspNet.Identity.Identityextensions to use this method
– Gustavo Santos
Already use, using Microsoft.AspNetCore.Identity;
– Mariana
You’re giving a
new
in theApplicationUser
this will generate a new ID, you need to retrieve the current user, as answered in the question:– Barbetta
It seems to me you need to do
CR.ApplicationUser = a;
instead ofCR.FuncionarioId = a.Id;
. When you create a newApplicationUser
Id does not exist. It will only exist afterSaveChanges
.– Pagotti