I want a write a custom function to find a particular property from identity user model. Say I want to find a user with a specified phone number. How to do so..???
Asked
Active
Viewed 1,040 times
1 Answers
3
You need to extend the UserStore class, something like below
public interface IUserCustomStore<TUser> : IUserStore<TUser, string>, IDisposable where TUser : class, Microsoft.AspNet.Identity.IUser<string>
{
Task<TUser> FindByPhoneNumberAsync(string phoneNumber);
}
namespace AspNet.Identity.MyCustomStore
{
public class UserStore<TUser> : Microsoft.AspNet.Identity.EntityFramework.UserStore<TUser>, IUserCustomStore<TUser>
where TUser : Microsoft.AspNet.Identity.EntityFramework.IdentityUser
{
public UserStore(ApplicationDbContext context)
: base(context)
{
}
public Task<TUser> FindByPhoneNumberAsync(string phoneNumber)
{
//Your Implementation
}
}
public class UserStore<TUser> : IUserCustomStore<TUser> where TUser:IdentityUser
{
public virtual Task<TUser> FindByPhoneNumberAsync(string phoneNumber)
{
return _Users.Find(u => u.PhoneNumber == phoneNumber).FirstOrDefaultAsync();
}
}
}
Replace all occurrence of
using Microsoft.AspNet.Identity.EntityFramework
with
using AspNet.Identity.MyCustomStore
And then in the IdentityConfig.cs add a new method to ApplicationUserManager
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
//LEAVE ALL THE METHODS AS IT IS
public virtual Task<ApplicationUser> FindByPhoneNumberUserManagerAsync(string phoneNumber)
{
IUserCustomStore<ApplicationUser> userCustomStore = this.Store as IUserCustomStore<ApplicationUser>;
if (phoneNumber == null)
{
throw new ArgumentNullException("phoneNumber");
}
return userCustomStore.FindByPhoneNumberAsync(phoneNumber);
}
}
You can now call this in the controller like
var user = await UserManager.FindByPhoneNumberUserManagerAsync(model.phoneNumber);
(assuming you have added the phoneNumber property to RegisterViewModel)
Hope this helps.

Ravi A.
- 2,163
- 2
- 18
- 26
-
Sorry forgot to add. Answer is Updated now. – Ravi A. Aug 30 '16 at 03:45