I have had a look around for answers on this for Identity 3.0 and found little regarding getting a single user that has an int id.
I have an asp.net-core mvc6 project in which I have converted all users and roles with string id's to have integer ids.
Fine. that works. I have a UserAdminController with among other things an update or Edit action which passes an "int?" for the id.
public async Task<IActionResult> Edit(int? id)
In my service I want to get the user associated with the integer id... "1".
I wanted to use UserManger.FindByIdAsync(id) to get the user with that id.
The problem is, this requires a "string" id not an "int" id.
Using UserManger (if I can) how do I return a user with an integer and not a string id? there must be an elegant way to return a user?
Just flow your user identifier as a string...
var user = _userManager.FindByIdAsync("1");
... and Identity will internally convert it back to the key type you've configured when registering it in ConfigureServices
using TypeConverter
:
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var id = ConvertIdFromString(userId);
return Users.FirstOrDefaultAsync(u => u.Id.Equals(id), cancellationToken);
}
public virtual TKey ConvertIdFromString(string id)
{
if (id == null)
{
return default(TKey);
}
return (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString(id);
}
Aliz was on the right track however the methods he suggested dont exist in Identity 3.0.
This however does work using as a basis Aliz option number 1..
var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With