c# - 如何获取当前用户的 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.
解决方案
您在查询中使用的外键是错误的。
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");
字段名称取决于您的表结构。
推荐阅读
- javascript - 在其环境之外调用局部变量
- python - 加入两个字符串并摆脱列表正则表达式
- unix - 如何在Unix中根据某些条件顺序组合两个文件
- docker - Rasa:在 GCP 上构建自定义操作服务器映像
- python - EnvironmentError: HTTPSConnectionPool 同时在 docker 容器上安装 pip
- python - 如何从 Python 中的 InstagramAPI 开始?
- javascript - 使带有多选功能的 React-Select 在小屏幕上工作(无垂直扩展)
- reactjs - React.js:如何将列表框的 onchange 值传递给函数?
- php - SQlite在php中按两个日期排序
- javascript - 使用自定义角度指令扩展 ng-boostrap 弹出框组件