如何根据特定值查询数据库中的列 MVC ASP.NET Core

How to query a column in a database based on specific value MVC ASP.NET Core

这可能是一个明显的答案,但我想得太多了,但我需要帮助从共享 属性.

的数据库中检索值

我的数据库:

这个特定的 MenuItems 数据库包含菜单项和指向我的餐厅数据库的链接。有一个 RestaurantID 列表示该项目属于哪个餐厅。 非常简单,但仅举个例子:ID 为 1 的鸡块属于 ID 为 1 的餐厅。

我需要执行查询以检索共享相同 RestaurantID 的菜单项列表。因此,例如:由于我正在查询 RestuarantID == 1 的项目,它将从数据库中检索 9 个项目。我在下面的函数中挑出公共值时遇到问题:

  public async Task<IActionResult> GetRestaurantOneVals()
        {
            int id = 1;              //Restuarant one's ID is == 1

            var menuItem = await _context.MenuItems
                .Include(s => s.Restaurant)
                .AsNoTracking()
                .FirstOrDefaultAsync(nameof => nameof.Restaurant.ID == id);
            
            var restaurantList = menuItem;
            
            return View(menuItem);
        }

这里是完整的控制器:

MenuItemsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using EasyEats.Data;
using EasyEats.Models;

namespace EasyEats.Controllers
{
    public class MenuItemsController : Controller
    {
        private readonly EasyEatsContext _context;

        public MenuItemsController(EasyEatsContext context)
        {
            _context = context;
        }

        // GET: MenuItems
        public async Task<IActionResult> Index()
        {
            var easyEatsContext = _context.MenuItems.Include(m => m.Restaurant);
            return View(await easyEatsContext.ToListAsync());
        }

        // GET: MenuItems/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var menuItem = await _context.MenuItems
                .Include(m => m.Restaurant)
                .FirstOrDefaultAsync(m => m.ID == id);
            if (menuItem == null)
            {
                return NotFound();
            }

            return View(menuItem);
        }

        public async Task<IActionResult> GetRestaurantOneVals()
        {
            int id = 1;                  //Restuarant one's ID is == 1

            var pleaseGod = await _context.MenuItems

            var menuItem = await _context.MenuItems
                .Include(s => s.Restaurant)
                .AsNoTracking()
                .FirstOrDefaultAsync(nameof => nameof.Restaurant.ID == id);
            
            var restaurantList = menuItem;
            
            return View(menuItem);
        }

        // GET: MenuItems/Create
        public IActionResult Create()
        {
            ViewData["RestaurantID"] = new SelectList(_context.Restaurants, "ID", "ID");
            return View();
        }

        // POST: MenuItems/Create
     
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,ItemName,ItemDescription,ItemImagePath,Price,RestaurantID")] MenuItem menuItem)
        {
            if (ModelState.IsValid)
            {
                _context.Add(menuItem);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["RestaurantID"] = new SelectList(_context.Restaurants, "ID", "ID", menuItem.RestaurantID);
            return View(menuItem);
        }

        // GET: MenuItems/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var menuItem = await _context.MenuItems.FindAsync(id);
            if (menuItem == null)
            {
                return NotFound();
            }
            ViewData["RestaurantID"] = new SelectList(_context.Restaurants, "ID", "ID", menuItem.RestaurantID);
            return View(menuItem);
        }

        // POST: MenuItems/Edit/5
      
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,ItemName,ItemDescription,ItemImagePath,Price,RestaurantID")] MenuItem menuItem)
        {
            if (id != menuItem.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(menuItem);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MenuItemExists(menuItem.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["RestaurantID"] = new SelectList(_context.Restaurants, "ID", "ID", menuItem.RestaurantID);
            return View(menuItem);
        }

        // GET: MenuItems/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var menuItem = await _context.MenuItems
                .Include(m => m.Restaurant)
                .FirstOrDefaultAsync(m => m.ID == id);
            if (menuItem == null)
            {
                return NotFound();
            }

            return View(menuItem);
        }

        // POST: MenuItems/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var menuItem = await _context.MenuItems.FindAsync(id);
            _context.MenuItems.Remove(menuItem);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool MenuItemExists(int id)
        {
            return _context.MenuItems.Any(e => e.ID == id);
        }
    }
}

MenuItem.cs 型号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace EasyEats.Models
{
    public class MenuItem
    {
        public int ID { get; set; }

        [Display(Name = "Item Name")]
        public string ItemName { get; set; }

        [Display(Name = "Item Description")]
        public string ItemDescription { get; set; }
        public string ItemImagePath { get; set; }
        public decimal Price { get; set; }
        public int RestaurantID { get; set; }
        public virtual Restaurant Restaurant { get; set; }
        public virtual CartItem CartItem { get; set; }

    }
}

您正在使用 FirstOrDefaultAsync(),它将检索与给定参数匹配的第一个元素,但您想要 return 与参数匹配的整个列表。变化:

var menuItem = await _context.MenuItems
             .Include(s => s.Restaurant)
             .AsNoTracking()
             .FirstOrDefaultAsync(nameof => nameof.Restaurant.ID == id);

对此你GetRestaurantOneVals()方法:

var menuItems = await _context.MenuItems
              .Include(s => s.Restaurant)
              .AsNoTracking()
              .Where(x => x.Restaurant.Id == id)
              .ToListAsync();

.Where() 将获取与给定语句匹配的所有对象,ToList() 将从查询中创建一个 List<T>

那么就return View(menuItems);.