I have a Core 2.0 project that has reached the point where I need to start linking users to the data I have. It started as a one user test bed that now requires me to have multiple per user.
User Model:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Balance> Balances { get; set; }
}
Balance model:
public virtual ApplicationUser User { get; set; }
...
ApplicationDbContext.cs:
//Users to balances
builder.Entity<ApplicationUser>()
.HasMany(b => b.Balances)
.WithOne(u => u.User);
In my code, when creating a new Balance, I cannot figure out how to link my current logged in user:
var myNewBalance = new Balance();
myNewBalance.User = User;
^ boom
How do I relate Balances to the currently logged in user?
The User
property you've highlighted in your question is a ClaimsPrincipal
that belongs to the ControllerBase
class. The User
property on your Balance
class is an ApplicationUser
, which is not compatible with ClaimsPrincipal
. You already know this, but I'm just making it explicit in order to explain what you need to do.
As you are using ASP.NET Core Identity here, you can use the UserManager
class, which is available using dependency injection. UserManager
contains a function, GetUserAsync
, that can convert your ClaimsPrincipal
into the corresponding ApplicationUser
.
Here's some code:
public class SomeController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public SomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> SomeAction()
{
var myNewBalance = new Balance();
myNewBalance.User = await _userManager.GetUserAsync(User);
return View(); // etc, etc.
}
}
The key points are the use of the generic UserManager
that uses ApplicationUser
and then the invocation of GetUserAsync
using the User
(ClaimsPrincipal
) property.