首页 > 解决方案 > 如何获取当前用户的 SelectList

问题描述

我正在尝试从数据库中获取客户/产品/类别的选择列表。选择列表将仅显示当前用户/当前登录用户的客户/产品/类别的选择列表。

但我只得到属于当前登录用户的第一项。

在数据库中,每个用户都有applicationUserId

我应该在选择列表中获取当前用户的所有客户/类别/产品列表

 public IActionResult Create()
        {
            var currentUser = _userManager.GetUserAsync(HttpContext.User);

            ViewData["CustomerId"] = new SelectList(_context.Customers.Where(c => c.ID == currentUser.Id), "ID", "Name") ;


            ViewData["ProductId"] = new SelectList(_context.Products.Where(p => p.ProductId == currentUser.Id), "ProductId", "ProductName");


            ViewData["CategoryId"] = new SelectList(_context.Categories.Where(p =>p.CategoryId == currentUser.Id) , "CategoryId", "CategoryName");

            return View();
        }

更新代码

 public IActionResult Create()
        {
            var currentUser = _userManager.GetUserAsync(HttpContext.User);

            string userId = currentUser.Id.ToString();
            ViewData["CustomerId"] = new SelectList(_context.Customers.Where(c => c.ApplicationUserId == userId), "ID", "Name");

            ViewData["ProductId"] = new SelectList(_context.Categories.Where(p => p.ApplicationUserId == userId), "ProductId", "ProductName");

            ViewData["ProductId"] = new SelectList(_context.Products.Where(p => p.ApplicationUserId == userId), "ProductId", "ProductName");

            return View();
        }

更新代码后,我得到了

InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.

标签: c#asp.net-mvcentity-frameworkasp.net-coreentity-framework-core

解决方案


您在查询中使用的外键是错误的。

ViewData["ProductId"] = new SelectList(_context.Products.Where(p => p.ProductId == currentUser.Id), "ProductId", "ProductName");

而不是这个,它应该是,

ViewData["ProductId"] = new SelectList(_context.Products.Where(p => p.UserId == currentUser.Id), "ProductId", "ProductName");

字段名称取决于您的表结构。


推荐阅读