How to get SelectList for the current user

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

Question

I am trying to get the selectlist of customers/products/categories from the database. the selectlist will only show the selectlist of customer/product/categories of the current user/current logged in user.

But I am only getting the first item belonging to the current logged user.

In the database, each users has applicationUserId

I am supposed to get all the list of customer/category/product of the current user in a selectlist

 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();
        }

Updated code

 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();
        }

after updating the code, I got

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.
1
1
10/9/2019 3:50:09 PM

Popular Answer

The foreign key you used in your query is wrong.

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

instead of this it should be like,

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

The field name depends on your table structure.

3
10/9/2019 3:04:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow