Microsoft.Data.SqlClient.SqlException:'在 ASP.Net core 中运行时列名无效

问题描述 投票:0回答:1

Screenshot of error我收到一个指向 ItemsService 中下面的“GetAllItems()”方法的 SQLException。 “无效的列名称 OrderID1”

我有两个实体,订单和商品,我希望与每个商品关联的 OrderID 显示在商品视图 (CRUD) 中

 public IEnumerable<Item> GetAllItems()
 {
     return _context.Items.ToList();
 }

商品服务

using iText.Layout.Borders;
using OrderEase.Models;

namespace OrderEase.Data.Services
{
    public class ItemsService : IItemsService
    {
        private readonly OrderDbContext _context;
        public ItemsService(OrderDbContext context)
        {
            _context = context;
        }

        public Item GetItemByID(int ItemID)
        {
            var item = _context.Items.Find(ItemID);

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));  
            }
            return item;
        }

        public IEnumerable<Item> GetAllItems()
        {
            return _context.Items.ToList();
        }

        public void CreateItem(Item item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            _context.Items.Add(item);
            _context.SaveChanges();
        }

        public void UpdateItem(Item item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));    
            }
            _context.Items.Update(item);
            _context.SaveChanges();
        }

        public void DeleteItem(int ItemID)
        {
            var ItemToDelete = _context.Items.Find(ItemID);
            if (ItemToDelete != null)
            {
                _context.Items.Remove(ItemToDelete);
                _context.SaveChanges();
            }
        }

        public bool ItemExists(int ItemID)
        {
            throw new NotImplementedException();
        }
    }
}

IItems服务

using OrderEase.Models;

namespace OrderEase.Data.Services
{
    public interface IItemsService
    {
        Item GetItemByID(int ItemId);
        IEnumerable<Item> GetAllItems();
        void CreateItem(Item item);
        void UpdateItem(Item item);
        void DeleteItem(int ItemID);
        bool ItemExists (int ItemID);
    }
}

物品控制器

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 OrderEase.Data;
using OrderEase.Data.Services;
using OrderEase.Models;

namespace OrderEase.Controllers
{
    public class ItemsController : Controller
    {
        private readonly IItemsService _itemsService;
        private readonly IOrdersService _ordersService;
        private SelectList OrderIDList;

        public ItemsController(IItemsService itemsService, IOrdersService ordersService)
        {
            _itemsService = itemsService;
            _ordersService = ordersService;
        }

        // GET: Items
        public IActionResult Index()
        {
            var items = _itemsService.GetAllItems();
            return View(items);
        }

        // GET: Items/Details/5
        public IActionResult Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var item = _itemsService.GetItemByID(id.Value);

            if(item == null)
            {
                return NotFound();
            }
            return View(item);
        }

        // GET: Items/Create
        public IActionResult Create()
        {
            var Orders = _ordersService.GetAllOrders();
            var orderIDList = new SelectList(Orders, "OrderID", "OrderID");
            var item = new Item
            {
                OrderIDList = orderIDList
            };

            return View(item);
        }

        // POST: Items/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("ItemID,ItemName,Price,QuantityInStock,OrderID")] Item item)
        {
            if (ModelState.IsValid)
            {
                _itemsService.CreateItem(item);
                return RedirectToAction(nameof(Index));
            }
            return View(item);
        }

        // GET: Items/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var item = _itemsService.GetItemByID(id.Value);

            if (item == null)
            {
                return NotFound();
            }

            var Orders = _ordersService.GetAllOrders();
            var orderIDList = new SelectList(Orders, "OrderID", "OrderID");
            {
                OrderIDList = orderIDList;
            };

            return View(item);
            
        }

        // POST: Items/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, [Bind("ItemID,ItemName,Price,QuantityInStock,OrderID")] Item item)
        {
            if (id != item.ItemID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _itemsService.UpdateItem(item);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_itemsService.ItemExists(item.ItemID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(item);
        }

        // GET: Items/Delete/5
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var item = _itemsService.GetItemByID(id.Value);

            if (item == null)
            {
                return NotFound();
            }
            return View(item);
        }

        // POST: Items/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            if (!_itemsService.ItemExists(id))
            {
                return Problem("Entity set 'OrderDbContext.Items'  is null.");
            }
           _itemsService.DeleteItem(id);
            return RedirectToAction(nameof(Index));
        }

        private bool ItemExists(int id)
        {
          return (_itemsService.ItemExists(id));
        }
    }
}

商品型号

using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace OrderEase.Models
{
    public class Item
    {
        [Key]
        [Display(Name = "Item ID")]
        public int ItemID { get; set; }

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

        [Display(Name = "Quantity in stock")]
        [Required(ErrorMessage = "Quantity in stock is required")]
        [Range(0, int.MaxValue, ErrorMessage = "Quantity must be non-negative.")]
        public int QuantityInStock { get; set; }

        //One-to-Many Relationship with Order
        [Display(Name ="Order ID")]
        public int OrderID { get; set; } //Foreign Key referecing Order
        public virtual Order Order { get; set; }

        //ViewModel-related properties
        [NotMapped]
        [ForeignKey("SelectedOrderID")]
        public int SelectedOrderID { get; set; }

        [NotMapped]
        [Display(Name = "Order ID List")]
        public SelectList OrderIDList { get; set; }


    }
}

这是我的 DbContext 类

使用 Microsoft.EntityFrameworkCore; 使用 OrderEase.Models;

命名空间 OrderEase.Data { 公共类 OrderDbContext :DbContext { 公共 OrderDbContext(DbContextOptions 选项):基(选项) {

    }

    //Configure Relationships
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Using Fluent API for Configuration
        modelBuilder.Entity<Order>()
            .HasKey(o => o.OrderID); //Configure Primary Key
        
        modelBuilder.Entity<Order>()
            .Property(o => o.Quantity)
            .IsRequired();

        modelBuilder.Entity<Order>()
            .Property(o => o.TotalPrice)
            .IsRequired()
            .HasPrecision(18, 2);

        modelBuilder.Entity<Order>()
            .Property(o => o.OrderDate)
            .IsRequired();

        modelBuilder.Entity<Order>()
            .Property(o => o.DeliveryDate)
            .IsRequired();


        modelBuilder.Entity<Order>()
            .Property(o => o.Supplier)
            .IsRequired()
            .HasMaxLength(255);

        //One-to-Many Relationship
        modelBuilder.Entity<Order>()
            .HasMany(o => o.Items)
            .WithOne(i => i.Order).HasForeignKey(i => i.OrderID);

        //Item Configuration
        modelBuilder.Entity<Item>()
            .HasKey(i => i.ItemID);

        modelBuilder.Entity<Item>()
            .Property(i => i.ItemName)
            .IsRequired()
            .HasMaxLength(255);

        modelBuilder.Entity<Item>()
            .Property(i => i.Price)
            .IsRequired()
            .HasPrecision(18, 2);

        modelBuilder.Entity<Item>()
            .Property(i => i.QuantityInStock)
            .IsRequired();

        //Relationship
        modelBuilder.Entity<Item>()
            .HasOne(i => i.Order)
            .WithMany(o => o.Items)
            .HasForeignKey(i => i.OrderID);

        base.OnModelCreating(modelBuilder);
    }

    //Defining Tables

    public DbSet<Order> Orders { get; set; }
    public DbSet<Item> Items { get; set; }
}

}

请协助确定此错误的根本原因和解决方案。 请耐心等待,我还在学习中。 预先感谢。

查看代码的其余部分https://github.com/Bless-Siba/OrderEase-Final/tree/master/Models

Screenshot of Error

c# asp.net entity-framework entity-framework-core
1个回答
0
投票

当外键被多次(多个关系)使用时,列名后跟一个数字,如

OrderID1

在您的情况下,外键属性

Item.OrderID
用于这两个关系:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...
    modelBuilder.Entity<Order>()
        .HasMany(o => o.Items)
        .WithOne(i => i.Order).HasForeignKey(i => i.OrderID);
    ...
    modelBuilder.Entity<Item>()
        .HasOne(i => i.Order)
        .WithMany(o => o.Items)
        .HasForeignKey(i => i.OrderID);
    ...
}

要解决该问题,您需要删除一个。

© www.soinside.com 2019 - 2024. All rights reserved.