【问题标题】:C# Implementing the CRUD operations in ControllerC# 在 Controller 中实现 CRUD 操作
【发布时间】:2015-11-10 00:26:10
【问题描述】:

我正在尝试为我的数据库实现创建、删除和编辑方法,但我不知道如何。我以为 Visual Studio 会自己生成它,但我遇到了很多错误。

我认为错误的主要原因是我如何使用 id 来查找我的产品和类别。我试过了

  • 类别类别 = db.Categories.Find(id);
  • Category category = db.Categories.Find(new Category() { Id = id });

但它们都不起作用。

我已在 Controllers/CategoryController.cs 中标记了错误。

错误列表(右键单击 -> 在新选项卡中打开图像)

模型/Product.cs

using System.Collections.Generic;


namespace Inventory.Models
{
    public class Product
    {
        public int Id { get; set; }
        public int CategoryId { get; set; }
        public string Brand { get; set; }
        public string Name { get; set; }
        public string Barcode { get; set;}
        public decimal Price { get; set; }
        public List<Category> Categories { get; set; }
    }
}

Models/Category.cs

using System.Collections.Generic;

namespace Inventory.Models
{
    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<Product> Products { get; set; } 
    }
}

控制器/CategoryController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Inventory.DAL;
using Inventory.Models;

namespace Inventory.Controllers
{
    public class CategoryController : Controller
    {
        private InventoryContext db = new InventoryContext();

        // GET: Category
        public ActionResult Index()
        {
            return View(db.Categories.ToList());
        }

        // GET: Category/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Category category = db.Categories.Find(id);  <--Line 31 Error 3 and 4
            if (category == null)
            {
                return HttpNotFound();
            }
            return View(category);
        }

        // GET: Category/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Category/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                db.Categories.Add(category);
                db.SaveChanges();      <-- Line 55 Error 5
                return RedirectToAction("Index");
            }

            return View(category);
        }

        // GET: Category/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Category category = db.Categories.Find(id);<--Line 69 Error 6 and 7
            if (category == null)
            {
                return HttpNotFound();
            }
            return View(category);
        }

        // POST: Category/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                db.Entry(category).State = EntityState.Modified; <--Line 86 Error 8
                db.SaveChanges(); <--Line 87 Error 9
                return RedirectToAction("Index");
            }
            return View(category);
        }

        // GET: Category/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Category category = db.Categories.Find(id); <--Line 100 Error 10 and 11
            if (category == null)
            {
                return HttpNotFound();
            }
            return View(category);
        }

        // POST: Category/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Category category = db.Categories.Find(id); <--Line 113 Error 12 and 13
            db.Categories.Remove(category);
            db.SaveChanges(); <--Line 115 Error 14 
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose(); <--Line 123 Error 15
            }
            base.Dispose(disposing);
        }
    }
}

DAL/InventoryContext.cs

using System.Collections.Generic;
using Inventory.Models;
using System.Linq;

namespace Inventory.DAL
{
    public class InventoryContext
    {
        public List<Product> Products { get; set; }
        public List<Category> Categories { get; set; }

        public InventoryContext()
        {
            Products = new List<Product>
            {
            new Product{Id=1,CategoryId=1,Brand="Coca Cola", Name="Coca Cola",Barcode="00001",Price=150},
            new Product{Id=2,CategoryId=1,Brand="Pepsi", Name="Pepsi",Barcode="00011",Price=150},
            new Product{Id=3,CategoryId=2,Brand="Homebrand", Name="Baked Beans",Barcode="0002",Price=250},
            new Product{Id=4,CategoryId=2,Brand="Homebrand", Name="Baked Patatos",Barcode="0022",Price=250}

            };
            Categories = new List<Category>
            {
            new Category{ID=1, Name="Drink", Products = Products.Where(p => p.CategoryId == 1).ToList() },
            new Category{ID=2,Name="Canned Food", Products = Products.Where(p => p.CategoryId == 2).ToList() }

            };
            foreach (var product in Products)
                product.Categories = Categories.Where(c => c.ID == product.CategoryId).ToList();

        }
    }
}

【问题讨论】:

  • 错误消息表明int?(可为空的 int)与Inventory.Models.Category 不同。从那里开始。
  • 这就是我感到困惑的地方。如果我不能使用 int 来指定 ID,那我该怎么做。

标签: c# asp.net visual-studio-2013 relational-database crud


【解决方案1】:

问题出在您的 InventoryContext 中。需要继承自 DbCntext

如下更改您的 Inventorycontext:

public class InventoryContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    public InventoryContext()
    {

        foreach (var product in Products)
            product.Categories = Categories.Where(c => c.ID == product.CategoryId).ToList();

    }
}

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 2019-12-15
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多