c# - 如何获取当前用户的SelectList

标签 c# asp.net-mvc entity-framework asp.net-core entity-framework-core

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

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

在数据库中,每个用户都有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.

最佳答案

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

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");

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

关于c# - 如何获取当前用户的SelectList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58307062/

相关文章:

c# - C# 中的图像 URL 验证

javascript - ASP.NET MVC AJAX 调用返回值以从 Controller 查看

c# - 使用经度和纬度查找给定距离内的所有附近客户

c# - LongListSelector 更改 ItemTemplate

c# - 在 telerik RadSpreadSheet 中,如何从单元格索引或选择中获取单元格名称?

c# - 泛型传递类型成员以对泛型集合进行操作

css - 使用 Knockoutjs 获取设置值属性

asp.net-mvc - 在每个请求上使用基于角色的自定义身份验证查询数据库的正确方法 ASP.NET MVC

c# - 如何在附加到 DBContext 之前单独通过属性检索 EF 4 代码优先实体的 [Key]?

c# - 在 EntityFramework 中选择每个组中的前 n 行