简体   繁体   中英

.NET C# CRUD operations work but never gets updated in the Database

My Create and Delete operations are proccessed succesfully with no errors but does nothing. When I try to create a new Product and save it, it doesn't show up on my table. When I try to delete a product, it doesn't get deleted.

I believe the problem is in my InventoryContext.cs file on this line:

public class InventoryContext : System.Data.Entity.DbContext

I had to add System.Data.Entity.DbContext for db.SaveChanges() to not show errors.

When I edit some Products and save it, it gives me this:

在此处输入图片说明

ProductController.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 ProductController : Controller
        {
            private InventoryContext db = new InventoryContext();

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

        public ActionResult Details(int id)
        {
            Product product = db.Products.FirstOrDefault(c => c.Id == id);

            // there error handling should be better than this
            if (product == null)
                return HttpNotFound();

            return View(product);
        }

        // GET: Product/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Product product = db.Products.FirstOrDefault(c => c.Id == id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,CategoryId,Brand,Name,Barcode,Price")] Product product)
        {
            if (ModelState.IsValid)
            {
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(product);
        }

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


        [HttpPost, ActionName("Create")]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,CategoryId,Brand,Name,Barcode,Price")] Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(product);
        }


        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Product product = db.Products.FirstOrDefault(c => c.Id == id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Product product = db.Products.FirstOrDefault(c => c.Id == id);
            db.Products.Remove(product);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }


        public ActionResult Assign(int productId, int categoryId)
        {
            Product product = db.Products.FirstOrDefault(p => p.Id == productId);
            product.CategoryId = categoryId;
            return RedirectToAction("Index");
        }


    }
}

InventoryContext.cs

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

namespace Inventory.DAL
{
    public class InventoryContext : System.Data.Entity.DbContext
    {
        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();

        }
    }
}

In the InventoryContext.cs file please check by adding the below lines.

public System.Data.Entity.DbSet Products {get;set;} public System.Data.Entity.DbSet Category{get;set;}

Refer the below links for resolution. http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-a-model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM