【问题标题】:How to query a column in a database based on specific value MVC ASP.NET Core如何根据特定值 MVC ASP.NET Core 查询数据库中的列
【发布时间】:2021-03-15 00:26:38
【问题描述】:

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

我的数据库:

这个特定的 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 是做什么的?是否有替代方法可以为您提供 list 条目?
  • @mjwills FirstOrDefauktAsync 返回序列的第一个元素,如果序列没有元素,则返回默认值。我想我可能试图查询错误,我的方法似乎过于复杂。
  • 请注意,如果您有兴趣,RestaurantId 列称为Foreign Key

标签: c# sql asp.net asp.net-mvc model-view-controller


【解决方案1】:

您正在使用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&lt;T&gt;

那么只需return View(menuItems);

【讨论】:

  • 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多