Reputation: 115
I have a Identity tables like AspNetUsers and others. I created migration Files with foreign key UserID to Id from AspNetUsers table for save files in Files table with logged in user Id. But in my FileManager View I see all files from Files table, but I need to display files only with UserID = Id from AspNetUsers (I mean with Id of logged in user). How Can I do it?
I think I need to edit some information in FileManager function but I'm not confident in it. If you need more code from the controller or other files in my ASP.NET Core project I can get it to you.
This code from my WorkSpaceController
that has other functions with uploading new file and other things, but this FileManager
function get data from context in var and displays on the FileManagerView
:
private readonly TextCloudContext Context;
public IActionResult FileManager()
{
var items = Context.Files.ToList();
return View(items);
}
This is TextCloudContext
code:
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);
}
}
}
Hope you can help me guys! Also, files dbo has UserId foreign key that references to Id in AspNetUsers table. I create Files table using Add-Migration command and Update-Database, so it works well and store files with current user Id, but I need to display information in ListRazorView (FileManager.cshtml) only for current logged in user.
Upvotes: 0
Views: 1105
Reputation: 27803
in my FileManager View I see all files from Files table, but I need to display files only with UserID = Id from AspNetUsers (I mean with Id of logged in user). How Can I do it?
To achieve the above requirement, you can try to call UserManager.GetUserId(ClaimsPrincipal) method to get user's id, then query files based on retrieved user id, like below.
//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);
Upvotes: 1