gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:21 25 4
gpt4 key购买 nike

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com