[英]How can I access my AppUser properties that are references to other objects? (ASP.NET/EFCore)
I have an AppUser class that inherits from IdentityUser and contains an Inventory object:我有一个 AppUser 类,它继承自 IdentityUser 并包含一个 Inventory 对象:
public class AppUser : IdentityUser
{
public InventoryModel? Inventory { get; set; }
}
I've been using this line to get the current user with all their properties:我一直在使用这条线来获取当前用户的所有属性:
var user = await _userManager.GetUserAsync(User);
Any primitive data types I put in AppUser can be accessed this way, but it seems to be lazy loading and not bringing the inventory along with it.我在 AppUser 中放入的任何原始数据类型都可以通过这种方式访问,但它似乎是延迟加载并且没有将库存带入其中。 I have manually queried my database and I see that the user I'm getting has an Inventory.InventoryId of 14 (primary key identifier for the Inventory class), but when I use the above statement to get the user, their Inventory is always null.
我手动查询了我的数据库,我看到我得到的用户的 Inventory.InventoryId 为 14(Inventory 类的主键标识符),但是当我使用上述语句获取用户时,他们的 Inventory 始终为空.
Is there some kind of ".Include()" that can be used with GetUserAsync?是否有某种“.Include()”可以与 GetUserAsync 一起使用? Is there another way I should be doing this?
我应该这样做吗?
For anyone with this same issue looking for a quick fix:对于有同样问题并寻求快速解决方案的任何人:
As Eldar suggested, I injected the ApplicationDbContext
and then did something like this:正如 Eldar 所建议的,我注入了
ApplicationDbContext
,然后做了这样的事情:
//get lazy-loaded current user using the usermanager
var lazyUser = await _userManager.GetUserAsync(User);
//get current user with includes using the ApplicationDbContext
//and the Id from the current user I already grabbed
var user = await _context.AppUsers.Where(u => u.Id == lazyUser.Id)
.Include(u => u.Inventory)
.SingleOrDefaultAsync();
It's pretty inelegant but technically it accomplish what I wanted to accomplish.这很不优雅,但从技术上讲,它完成了我想要完成的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.