簡體   English   中英

ASP.NET Core MVC如何通過UserID外鍵顯示List Razor Template中SQL表的數據

[英]ASP NET Core MVC how to display data from SQL table in List Razor Template by UserID foreign key

我有一個身份表,如 AspNetUsers 和其他人。 我從 AspNetUsers 表創建了帶有外鍵 UserID 到 Id 的遷移文件,用於將文件保存在具有登錄用戶 ID 的 Files 表中。 但是在我的 FileManager 視圖中,我看到了文件表中的所有文件,但我只需要顯示來自 AspNetUsers 的 UserID = Id 的文件(我的意思是登錄用戶的 Id)。 我該怎么做?

我想我需要在 FileManager function 中編輯一些信息,但我對此沒有信心。 如果您需要 controller 中的更多代碼或我的 ASP.NET 核心項目中的其他文件,我可以為您提供。

這段來自我的WorkSpaceController的代碼具有上傳新文件和其他東西的其他功能,但是這個FileManager function 從 var 中的上下文獲取數據並顯示在FileManagerView上:

private readonly TextCloudContext Context;

public IActionResult FileManager()
{
    var items = Context.Files.ToList();
    return View(items);
}

這是TextCloudContext代碼:

namespace TextCloud.Data
{
    public class TextCloudContext : IdentityDbContext<TextCloudUser>
    {
        public TextCloudContext(DbContextOptions<TextCloudContext> options) : base(options)
        {
        }

        public DbSet<File> Files { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

希望你們也能幫助我。 files dbo 具有引用 AspNetUsers 表中的 Id 的 UserId 外鍵,我使用 Add-Migration 命令和 Update-Database 創建文件表,因此它運行良好並使用當前用戶 Id 存儲文件。 但我只需要在 ListRazorView (FileManager.cshtml) 中顯示當前登錄用戶的信息。

在我的 FileManager 視圖中,我看到了文件表中的所有文件,但我只需要顯示來自 AspNetUsers 的 UserID = Id 的文件(我的意思是登錄用戶的 Id)。 我該怎么做?

為了實現上述需求,您可以嘗試調用UserManager.GetUserId(ClaimsPrincipal)方法獲取用戶的 id,然后根據檢索到的用戶 id 查詢文件,如下所示。

//get user id of current logged-in user 
var currentUserId = _userManager.GetUserId(User);

var items = Context.Files.Where(f => f.UserID == currentUserId).ToList();
return View(items);

暫無
暫無

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

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