11

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?

si2030
  • 3,895
  • 8
  • 38
  • 87
  • User are identified by a GUID which are strings, that's why the FindByIdAsync function takes a string as parameter, why do you want to use an int ? – Aliz May 02 '16 at 13:38
  • 2
    Set up my users to have int ids not GUIDs. I am passing an int id from the "Get" method to my service and need to return a user associated with that id.. I would like to use usermanager which I have available via dependency injection. – si2030 May 02 '16 at 14:00

2 Answers2

16

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);
}
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
6

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);
si2030
  • 3,895
  • 8
  • 38
  • 87
  • Not sure why this is marked as the correct answer - While this will work 90% of the time you can get some odd behaviour when mixing and matching UserManager retrieval to direct DBContext retrieval (which is what this is doing) when editing as each has it's own active context with changes. – Keith Jackson Mar 16 '21 at 09:40