Я пытаюсь реализовать методы создания, удаления и редактирования для своей базы данных, но я не знаю, как это сделать. Я думал, что Visual Studio создает его сам по себе, но я получаю много ошибок.C# Реализация CRUD-операций в контроллере
Я считаю, что основной причиной ошибок является то, как я использую идентификатор для поиска моих продуктов и категорий. Я пробовал
- Категория категории = db.Categories.Find (id);
- Категория категории = db.Categories.Find (новая категория() {Id = id});
, но оба они не работают.
Я указал на ошибки в контроллерах/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; }
}
}
Модели/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 (обнуляемое целое) не то же самое, что и 'Inventory.Models?. category'. Начните там. –
Вот что я смутил. Если я не могу использовать int, чтобы указать ID, то как я могу это сделать. – TykiMikk