Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Here's the exact error
Attaching an entity of type 'WebApplication3.student1' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

GO TO the method :Action Result Edit(student1 student1,FormCollection fc)

What I have tried:

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 WebApplication3;

namespace WebApplication3.Controllers
{
    public class student1Controller : Controller
    {
        private preet_testEntities db = new preet_testEntities();
  
        // GET: student1
        public ActionResult Index()
        {
           

            return View(db.student1.ToList());


        }
        //[HttpPost]
        //public string Index1(IEnumerable<student1> students)
        //{
        //    if (students.Count(x => x.hobbies) == 0)
        //    {
        //        return "please select a value";
        //    }
        //}
        // GET: student1/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            student1 student1 = db.student1.Find(id);
            if (student1 == null)
            {
                return HttpNotFound();
            }
            return View(student1);
        }

        // GET: student1/Create
        public ActionResult Create()
        {
            var list = new SelectList(new[]
                                             {
                                              new {ID="Reading",Name="Reading"},
                                              new{ID="Writing",Name="Writing"},
                                              new{ ID="Cricket",Name="Cricket"},
                                              new{ ID="Singing", Name="Singing"},
                                              new{ ID="Dancing", Name="Dancing" }
                                          },
                               "ID", "Name", 1);
            ViewBag.hobby = list;
            return View();
        }

        // POST: student1/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        
        public ActionResult Create(student1 student1,FormCollection fc)
        {
            if (ModelState.IsValid)
            {
                
                student1 obj = db.student1.Find(student1.student_id);
                if(obj!=null)
                {
                    obj.hobbies = fc["hobb"] != null ? fc["hobb"].ToString() : obj.hobbies;
                    db.SaveChanges();

                }

                if(obj==null)
                {
                    student1.hobbies = fc["hobb"].ToString();
                    db.Entry(student1).State = EntityState.Added;
                    db.SaveChanges();
                }
                    return RedirectToAction("Index");
            }

            var list = new SelectList(new[]
                                            {
                                              new {ID="Reading",Name="Reading"},
                                              new{ID="Writing",Name="Writing"}
                                          },
                              "ID", "Name", 1);
            ViewBag.hobby = list;


            return View(student1);
        }

        // GET: student1/Edit/5
        public ActionResult Edit(int? id)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            student1 student1 = db.student1.Find(id);
            if (student1 == null)
            {
                return HttpNotFound();
            }
            var list = new SelectList(new[]
                                             {
                                              new {ID="Reading",Name="Reading"},
                                              new{ID="Writing",Name="Writing"},
                                                new{ ID="Cricket",Name="Cricket"},
                                              new{ ID="Singing", Name="Singing"},
                                              new{ ID="Dancing", Name="Dancing" }
                                          },
                               "ID", "Name", 1);
            ViewBag.hobby = list;
            
            return View(student1);
        }

        // POST: student1/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit( student1 student1 ,FormCollection fc)
        {
            if (ModelState.IsValid)
            {

                student1 obj = db.student1.Find(student1.student_id);//.Find(student1.student_id);
                    if (obj != null)
                {
                    obj.hobbies = fc["hobb"] != null ? fc["hobb"].ToString() : obj.hobbies;
                    //db.Entry(student1).CurrentValues.SetValues(student1);
                    
                    db.Entry(student1).State = EntityState.Modified; //this is where error is generated
                    db.SaveChanges();

                }

                student1.hobbies = fc["hobb"].ToString();
                db.student1.AsNoTracking();
                db.Entry(student1).State = EntityState.Added;
          
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student1);
        }

        // GET: student1/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            student1 student1 = db.student1.Find(id);
            if (student1 == null)
            {
                return HttpNotFound();
            }
            return View(student1);
        }

        // POST: student1/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            student1 student1 = db.student1.Find(id);
            db.student1.Remove(student1);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
Posted
Updated 30-Nov-21 20:25pm
v4
Comments
[no name] 3-Dec-21 14:46pm    
In your case, the logical and clearer choice would be to simply use (DbSet) ".Add" for the new student in Create(). Trying to "attach", etc. "new" entities when the primary key hasn't been generated yet (by the DB) doesn't work very well.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900