簡體   English   中英

如何訪問引用其他對象的 AppUser 屬性? (ASP.NET/EFCore)

[英]How can I access my AppUser properties that are references to other objects? (ASP.NET/EFCore)

我有一個 AppUser 類,它繼承自 IdentityUser 並包含一個 Inventory 對象:

public class AppUser : IdentityUser
    {
        public InventoryModel? Inventory { get; set; }
    }

我一直在使用這條線來獲取當前用戶的所有屬性:

var user = await _userManager.GetUserAsync(User);

我在 AppUser 中放入的任何原始數據類型都可以通過這種方式訪問​​,但它似乎是延遲加載並且沒有將庫存帶入其中。 我手動查詢了我的數據庫,我看到我得到的用戶的 Inventory.InventoryId 為 14(Inventory 類的主鍵標識符),但是當我使用上述語句獲取用戶時,他們的 Inventory 始終為空.

是否有某種“.Include()”可以與 GetUserAsync 一起使用? 我應該這樣做嗎?

對於有同樣問題並尋求快速解決方案的任何人:

正如 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();

這很不優雅,但從技術上講,它完成了我想要完成的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM