How to load navigation properties on an IdentityUser with UserManager

前端 未结 3 1713
离开以前
离开以前 2020-12-03 05:01

I\'ve extended IdentityUser to include a navigation property for the user\'s address, however when getting the user with UserManager.FindByEmailAsync

3条回答
  •  -上瘾入骨i
    2020-12-03 05:04

    The short answer: you can't. However, there's options:

    1. Explicitly load the relation later:

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

      This will require issuing an additional query of course, but you can continue to pull the user via UserManager.

    2. Just use the context. You don't have to use UserManager. It just makes some things a little simpler. You can always fallback to querying directly via the context:

      var user = context.Users.Include(x => x.Address).SingleOrDefaultAsync(x=> x.Id == User.Identity.GetUserId());
      

    FWIW, you don't need virtual on your navigation property. That's for lazy-loading, which EF Core currently does not support. (Though, EF Core 2.1, currently in preview, will actually support lazy-loading.) Regardless, lazy-loading is a bad idea more often than not, so you should still stick to either eagerly or explicitly loading your relationships.

提交回复
热议问题