2

My question is based on the topic here but as I am not allowed to add comments there I guess I have to open a new thread.

In my ASP.NET Core backend I'm using ASP.NET Core Identity for the user management. It provides methods for user authentication with the help of the so-called user manager.

I now have troubles with using methods from the user manager on the one hand and loading custom Application User properties on the other hand.

Scenario as follows: the frontend sends via MVC controller (HTTP request) a login dto that contains an email address and a password. I now want to load the application user with the method FindByEmailAsync provided by the user manager. I wrap this method in a self-made application user repository where the user manager is injected by dependency injection and that has also access to the application context. As the user manager does not load custom properties when loading the user manager I have to do some additional stuff to load these properties, too.

I first tried to load the user completely via the context (not via user manager). That worked fine and the additional properties could be loaded, too. The problems started when afterwards trying to use the usermanager.CheckPasswordAsync method. I got an exception:

"the instance of entity ApplicationUser cannot be tracked because another instance with the same key value for id is already been tracked".

I think this resulted from using the context to load the user on the one hand and the user manager to perform the checkPassword. Then I tried to load the user with the FindByEmailAsync of the usermanager. Everything worked fine, no exceptions, but the custom properties have not been loaded. In the thread that I linked above there are some suggestions but none of them works for me.

  1. Suggestion:

    var user = await userManager.Users
      .Include(x => x.Address)
      .SingleAsync(x => x.NormalizedEmail == email);
    

userManager.Users is a IQueryable<Users> and does not contain an Include method.

  1. Suggestion:

    await context.Entry(user).Reference(x => x.Address).LoadAsync();
    

In my case the custom property (Certificates) is a collection so I used .Collection instead of .Reference, but got the following error:

"Navigation property 'Certificates' on entity of type 'ApplicationUser' cannot be loaded because the entity is not being tracked. Navigation properties can only be loaded for tracked entities."

Does anybody has a suggestion how to use the provided methods of the user manager and including custom properties to the application user?

Thank you!

Matheus Lacerda
  • 5,739
  • 11
  • 26
  • 41
MatterOfFact
  • 662
  • 2
  • 10
  • 25

1 Answers1

0

I faced the same Issue and noticed that it work when you load your DbContext before accessing to the custom property

var user = await userManager.Users;
_context.Users.Include(u => u.Address).FirstOrDefault(x => x.NormalizedEmail == email);

var adress = user.Address;