I see a lot of information on ASP.Net Core Identity and have been piecing together how to customize it, since I am building a site for use against an existing SQL Server database.
I have been able to customize my replacement for the AspNetUsers
table, and have new users saving properly. Since in the existing systems that use this database there are a couple of stored procedure calls that happen that wrap a lot of functionality, I would like to use the same approach. So I think that instead of the default call like this:
var result = await _userManager.CreateAsync(user, model.Password);
I would need something that can call one or more stored procedures to create the user. Should I inherit from UserManager
and override the CreateAsync
call? If so, can I use my existing user store? I'm a little fuzzy on what this looks like, WRT identity. Thanks!
You should keep using _userManager.CreateAsync
, but configure it in such a way that your own implementation of a UserStore
is used.
In Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services
.AddIdentity<MyUser>()
.AddUserStore<MyUserStore>();
}
Then, create a custom UserStore
, where you can call your context class (including calls to stored procedures):
public class MyUserStore : IUserStore<MyUser>
{
private MyContext _db;
public MyUserStore(MyContext db)
{
_db = db;
}
public async Task<IdentityResult> CreateAsync(MyUser user, CancellationToken cancellationToken)
{
// simply store entity in DB
user = _db.Users.Add(user).Entity;
await _db.SaveChangesAsync();
// or run stored procedure
await _db.Database.ExecuteSqlCommandAsync("usp_MyUserCreationStoredProcedure @p0, @p1", user.FirstName, user.LastName);
return IdentityResult.Success;
}
}
You can check the relevant documentation on how to create custom user stores for more information.