Warm tip: This article is reproduced from serverfault.com, please click

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

(c# - How to query a column in a database based on specific value MVC ASP.NET Core)

发布于 2020-12-03 00:53:07

这可能是我想过的一个显而易见的答案,但是我需要帮助从共享属性的数据库中检索值。

我的数据库: MenuItems数据库

这个特定的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; }

    }
}
Questioner
Ana Vanderwoodson
Viewed
0
jah 2020-12-03 09:30:07

你正在使用FirstOrDefaultAsync()它将检索与给定参数匹配的第一个元素,但是你想返回与参数匹配的整个列表。改变:

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