So, I created Asp.Net 6 Identity.
There is another table, where I have UserId field and it is a foreign key for the Application User (Identity Id).
I generated the controller from command line dotnet-asp-codegenerator. It created the form with field for Identity Id and it is visible/editable to the end user. I can make it hidden like <input type="hidden"... but I am sure this is not a solution.
How can I get Identity Id inside the controller and pass it to the Db?
I have tried some solutions, for example: User.Identity.GetUserId() - does not work
Models/ApplicationUser.cs
namespace App.Models
{
public class ApplicationUser : IdentityUser
{
public ICollection<Order> Order { get; set; } = null!;
}
}
Models/Order.cs
namespace App.Models
{
public class Order
{
public int Id { get; set; }
[StringLength(100)]
public string? Name { get; set; }
[StringLength(255)]
[DisplayName("Description")]
public string? Description { get; set; }
public string? UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser? User { get; set; }
}
}
Views/Order/Create.cshtml
...
<div class="form-group">
<label asp-for="UserId" class="control-label"></label>
<select asp-for="UserId" class ="form-control" asp-items="ViewBag.UserId"></select>
</div>
...
Controllers/OrderController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Region,AccessId,SecretKey,UserId")] Order order)
{
//??? how to get Identity Id and pass it to the order?!
if (ModelState.IsValid)
{
_context.Add(order);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", order.UserId);
return View(order);
}