Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend UserManager to include a search by custom field ASP.net core

I added FirstName, LastName, address, CardID and such to my application user for an ASP.net Core MVC application.

I would like to be able to add additional functions to search that database to the UserManager Class to search for the user based on those additional properties.

For example It already contains function for finding by Name (Username)

_userManager.FindByNameAsync("Mike123")

I would like the ability to find user object by CARDID

_userManager.FindByCardIDAsync("123456789")

or multiple users by Address

_userManager.FindByAddressAsync("123 Fake St. Real Town, USA")

I have successfully used this function

ApplicationUser User = _userManager.Users.FirstOrDefault(u => u.CardID == CardID);

I would still like to understand a way to extend that class or should I just create my own and inherit from it?

like image 999
Mike Schmidt Avatar asked Dec 04 '22 22:12

Mike Schmidt


1 Answers

What about Extension Methods? For example:

using System;
using System.Collections.Generic;
using System.Linq;
using ExampleProject.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace ExampleProject
{
    public static class UserManagerExtensions
    {
        public static async Task<ApplicationUser> FindByNameAsync(this UserManager<ApplicationUser> um, string name)
        {
            return await um?.Users?.SingleOrDefaultAsync(x => x.UserName == name);
        }

        public static async Task<ApplicationUser> FindByCardIDAsync(this UserManager<ApplicationUser> um, string cardId)
        {
            return await um?.Users?.SingleOrDefaultAsync(x => x.CardID == cardId);
        }

        public static async Task<ApplicationUser> FindByAddressAsync(this UserManager<ApplicationUser> um, string address)
        {
            return await um?.Users?.SingleOrDefaultAsync(x => x.Address == address);
        }
    }
}

But be aware, that is simple example and will work well only if Name/CardID/Address is unique...

I have used SingleOrDefaultAsync as a protection for the case when Name/CardID/Address is a not unique - but I suggest to rethink it once again... I suppose it will be hard to make address unique so perhaps you can find better criterium or you will return a collection of users?

like image 102
Lukasz Mk Avatar answered Jan 20 '23 01:01

Lukasz Mk