5

Is there drawbacks or advantages in using either UserManager or DbContext?

If I use this:

public class UserManager<TUser> : IDisposable where TUser : class public virtual Task<TUser> FindByIdAsync(string userId); 

Or if I use direct dbcontext like:

 var user = dbContext.Users.Where(x => x.Id == model.Id).FirstOrDefault(); // Login like this await HttpContext.SignInAsync(..) 

2 Answers 2

4

Today, you query your users from your database. What if you decided to delegate the authentication to an authorization server? I've seen this happen before: people decide to create a Web API to deal with authentication/authorization details. If you were using the DbContext directly, you would have to change everywhere you would be using it.

By using UserManager on the other hand, you would just have to change the implementation of your UserManager to use an HttpClient, to consume a Web API in order to query users, roles and other stuff needed to create your user Identity.

The UserManager encapsulates the implementation details through the IUserStore and some other interfaces. I'd avoid querying any of the Identity tables directly, even though it's very tentative.

Sign up to request clarification or add additional context in comments.

Comments

2

The main drawback if you use Entity Framework directly, is that you would have to change all references if you changed the store to something else.

ASP.NET Core Identity allows you to create custom stores in two steps:

  1. Creating a class that implements the required interfaces

    public class MyStore : IUserStore<ApplicationUser>, ... // many more { } 
  2. Replacing the Entity Framework stores by yours:

    // default services.AddIdentity(...).AddEntityFrameworkStores(); // yours services.AddIdentity(...).AddUserStore<MyStore>(); 

If you ever need to create a custom store because of business requirements or a data storage method not available in Entity Framework Core (or even willing to remove EF Core from the project), you'd be better off if you used the UserManager methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.