Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity 3.0 Getting a user by id when the id is "int"

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?

like image 349
si2030 Avatar asked May 02 '16 13:05

si2030


2 Answers

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);
}
like image 50
Kévin Chalet Avatar answered Oct 19 '22 12:10

Kévin Chalet


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);
like image 40
si2030 Avatar answered Oct 19 '22 13:10

si2030