public virtual void Delete(TEntity entityToDelete)
 {
     if (context.Entry(entityToDelete).State == EntityState.Detached)
     {
         dbSet.Attach(entityToDelete);
     }
     dbSet.Remove(entityToDelete);
 }
예제 #2
0
        public async Task <IActionResult> PutStudent(int id, Student student)
        {
            if (id != student.StudentID)
            {
                return(BadRequest());
            }

            _context.Entry(student).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #3
0
 public async Task <IActionResult> Put([FromODataUri] int key, Person update)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     if (key != update.PersonId)
     {
         return(BadRequest());
     }
     db.Entry(update).State = EntityState.Modified;
     try
     {
         await db.SaveChangesAsync();
     }
     catch (DbUpdateConcurrencyException)
     {
         if (!PersonExists(key))
         {
             return(NotFound());
         }
         else
         {
             throw;
         }
     }
     return(Updated(update));
 }
예제 #4
0
        public async Task <IActionResult> PutTeacher(int id, Teacher teacher)
        {
            if (id != teacher.Id)
            {
                return(BadRequest());
            }

            context.Entry(teacher).State = EntityState.Modified;

            try
            {
                await context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TeacherExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #5
0
        public ActionResult Edit([Bind(Include = "ID,LastName,FirstMidName,EnrollmentDate")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(student).State = EntityState.Modified;

                    // Read on Entity states and the attach and save changes methods
                    // The database context keeps track of whether entities in memory are in sync with their corresponding rows in the database, and this information determines what happens when you call the SaveChanges method. For example, when you pass a new entity to the Add method, that entity's state is set to Added. Then when you call the SaveChanges method, the database context issues a SQL INSERT command.
                    // In a desktop application, state changes are typically set automatically. In a desktop type of application, you read an entity and make changes to some of its property values. This causes its entity state to automatically be changed to Modified. Then when you call SaveChanges, the Entity Framework generates a SQL UPDATE statement that updates only the actual properties that you changed.+
                    // The disconnected nature of web apps doesn't allow for this continuous sequence. The DbContext that reads an entity is disposed after a page is rendered. When the HttpPost Edit action method is called, a new request is made and you have a new instance of the DbContext, so you have to manually set the entity state to Modified. Then when you call SaveChanges, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed.
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            // You were using DataException to try to identify errors that might be transient in order to give a friendly "try again" message. But now that you've turned on a retry policy, the only errors likely to be transient will already have been tried and failed several times and the actual exception returned will be wrapped in the RetryLimitExceededException exception.
            catch (RetryLimitExceededException ex)
            {
                // TODO: Read up on https://docs.microsoft.com/en-us/aspnet/aspnet/overview/developing-apps-with-windows-azure/building-real-world-cloud-apps-with-windows-azure/monitoring-and-telemetry#log
                Trace.TraceError(ex.Message);
                ModelState.AddModelError("", "Unable to save changes. Try again, and if problems persists see you system administrator.");
            }
            return(View(student));
        }
예제 #6
0
        public IHttpActionResult PutStudent(int id, Student student)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != student.StudentId)
            {
                return(BadRequest());
            }

            db.Entry(student).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #7
0
        public async Task <IActionResult> PutEscuela(int id, Escuela escuela)
        {
            using (var _context = new SchoolDBContext())
            {
                if (id != escuela.Id)
                {
                    return(BadRequest());
                }

                _context.Entry(escuela).State = EntityState.Modified;

                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EscuelaExists(id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(NoContent());
            }
        }
 public void EditStudent([FromBody] Student student)
 {
     using (var ctx = new SchoolDBContext())
     {
         ctx.Students.Attach(student);
         ctx.Entry(student).State = EntityState.Modified;
         ctx.SaveChanges();
     }
 }
 public void DeleteStudent([FromBody] int id)
 {
     using (var ctx = new SchoolDBContext())
     {
         var student = ctx.Students.FirstOrDefault(s => s.StudentId == id);
         ctx.Entry(student).State = EntityState.Deleted;
         ctx.SaveChanges();
     }
 }
예제 #10
0
 public void EditTest([FromBody] Test test)
 {
     using (var ctx = new SchoolDBContext())
     {
         ctx.Tests.Attach(test);
         ctx.Entry(test).State = EntityState.Modified;
         ctx.SaveChanges();
     }
 }
예제 #11
0
 public ActionResult Edit([Bind(Include = "Id,Title,Stream,Type,StartDate,EndDate")] Course course)
 {
     if (ModelState.IsValid)
     {
         db.Entry(course).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(course));
 }
 public ActionResult Edit([Bind(Include = "id,Name,Gender,IsChecked")] Person person)
 {
     if (ModelState.IsValid)
     {
         db.Entry(person).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(person));
 }
예제 #13
0
 public ActionResult Edit([Bind(Include = "Id,Description,MinSat")] Major major)
 {
     if (ModelState.IsValid)
     {
         db.Entry(major).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(major));
 }
예제 #14
0
 public ActionResult Edit([Bind(Include = "StudentId,StudentName")] Student student)
 {
     if (ModelState.IsValid)
     {
         db.Entry(student).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(student));
 }
예제 #15
0
 public ActionResult Edit([Bind(Include = "CourseID,CourseName,TeacherID")] Course course)
 {
     if (ModelState.IsValid)
     {
         db.Entry(course).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(course));
 }
 public ActionResult Edit([Bind(Include = "ID,School_Name,Address,Classes,Staff")] School school)
 {
     if (ModelState.IsValid)
     {
         db.Entry(school).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(school));
 }
예제 #17
0
 public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,BirthDate,TuitionFees,Course,ImageURL")] Student student)
 {
     if (ModelState.IsValid)
     {
         db.Entry(student).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(student));
 }
예제 #18
0
 public ActionResult Edit([Bind(Include = "TeacherID,Firstname,Lastname")] Teacher teacher)
 {
     if (ModelState.IsValid)
     {
         db.Entry(teacher).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(teacher));
 }
예제 #19
0
 public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,Subject,Course,ImageURL")] Trainer trainer)
 {
     if (ModelState.IsValid)
     {
         db.Entry(trainer).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(trainer));
 }
 public ActionResult Edit([Bind(Include = "Id,Title,Description,SubDate,OralMark,TotalMark,Course")] Assignment assignment)
 {
     if (ModelState.IsValid)
     {
         db.Entry(assignment).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(assignment));
 }
예제 #21
0
 public ActionResult Edit([Bind(Include = "Id,Description,MajorId")] Class @class)
 {
     if (ModelState.IsValid)
     {
         db.Entry(@class).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.MajorId = new SelectList(db.Majors, "Id", "Description", @class.MajorId);
     return(View(@class));
 }
 public ActionResult Edit([Bind(Include = "Id,Firstname,Lastname,MajorId,SAT")] Student student)
 {
     if (ModelState.IsValid)
     {
         db.Entry(student).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.MajorId = new SelectList(db.Majors, "Id", "Description", student.MajorId);
     return(View(student));
 }
예제 #23
0
        private static void Delete_Student(SchoolDBContext DB)
        {
            Console.WriteLine("Delete Old Student");
            Console.Write("Enter Student ID : ");
            Student student = new Student();

            student.ID = Convert.ToInt32(Console.ReadLine());

            DB.Students.Attach(student);
            DB.Entry(student).State = EntityState.Deleted;
            DB.SaveChanges();
        }
 public ActionResult Edit([Bind(Include = "Id,StudentId,ClassId,Grade")] Enrolled enrolled)
 {
     if (ModelState.IsValid)
     {
         db.Entry(enrolled).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ClassId   = new SelectList(db.Classes, "Id", "Description", enrolled.ClassId);
     ViewBag.StudentId = new SelectList(db.Students, "Id", "Firstname", enrolled.StudentId);
     return(View(enrolled));
 }
예제 #25
0
        private static void Update_Student(SchoolDBContext DB)
        {
            Console.WriteLine("Update Old Student");
            Console.Write("Enter Student ID : ");
            Student student = new Student();

            student.ID = Convert.ToInt32(Console.ReadLine());
            Console.Write("Name: ");
            student.Name = Console.ReadLine();
            Console.Write("Address: ");
            student.Address = Console.ReadLine();
            Console.Write("Phone: ");
            student.Phone = Console.ReadLine();

            DB.Students.Attach(student);
            DB.Entry(student).State = EntityState.Modified;
            DB.SaveChanges();
        }
        public ActionResult Edit([Bind(Include = "ID,Title,Credits,DepartmentID")] Course course)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(course).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (RetryLimitExceededException ex)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
            }

            ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "Name", course.DepartmentID);
            return(View(course));
        }
        public async Task <ActionResult> Edit(int?id, byte[] rowVersion)
        {
            string[] fieldsToBind = new string[] { "Name", "Budget", "StartDate", "InstructorID", "RowVersion" };

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var departmentToUpdate = await db.Departments.FindAsync(id);

            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                TryUpdateModel(deletedDepartment, fieldsToBind);
                ModelState.AddModelError(string.Empty,
                                         "Unable to save changes. The department was deleted by another user.");
                ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "FullName", deletedDepartment.InstructorID);
                return(View(deletedDepartment));
            }

            if (TryUpdateModel(departmentToUpdate, fieldsToBind))
            {
                try
                {
                    db.Entry(departmentToUpdate).OriginalValues["RowVersion"] = rowVersion;
                    await db.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                // If no rows are affected by the UPDATE command (no rows have the original RowVersion value), the Entity Framework throws a DbUpdateConcurrencyException exception, and the code in the catch block gets the affected Department entity from the exception object.
                catch (DbUpdateConcurrencyException ex)
                {
                    // This object has the new values entered by the user in its Entity property, and you can get the values read from the database by calling the GetDatabaseValues method.
                    var entry         = ex.Entries.Single();
                    var clientValues  = (Department)entry.Entity;
                    var databaseEntry = entry.GetDatabaseValues();

                    /// The GetDatabaseValues method returns null if someone has deleted the row from the database; otherwise, you have to cast the returned object to the Department class in order to access the Department properties. (Because you already checked for deletion, databaseEntry would be null only if the department was deleted after FindAsync executes and before SaveChanges executes.)
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save changes. The department was deleted by another user.");
                    }
                    // Next, the code adds a custom error message for each column that has database values different from what the user entered on the Edit page:
                    else
                    {
                        var databaseValues = (Department)databaseEntry.ToObject();

                        if (databaseValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", "Current value: "
                                                     + databaseValues.Name);
                        }
                        if (databaseValues.Budget != clientValues.Budget)
                        {
                            ModelState.AddModelError("Budget", "Current value: "
                                                     + String.Format("{0:c}", databaseValues.Budget));
                        }
                        if (databaseValues.StartDate != clientValues.StartDate)
                        {
                            ModelState.AddModelError("StartDate", "Current value: "
                                                     + String.Format("{0:d}", databaseValues.StartDate));
                        }
                        if (databaseValues.InstructorID != clientValues.InstructorID)
                        {
                            ModelState.AddModelError("InstructorID", "Current value: "
                                                     + db.Instructors.Find(databaseValues.InstructorID).FullName);
                        }
                        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                                 + "was modified by another user after you got the original value. The "
                                                 + "edit operation was canceled and the current values in the database "
                                                 + "have been displayed. If you still want to edit this record, click "
                                                 + "the Save button again. Otherwise click the Back to List hyperlink.");

                        // Finally, the code sets the RowVersion value of the Department object to the new value retrieved from the database. This new RowVersion value will be stored in the hidden field when the Edit page is redisplayed, and the next time the user clicks Save, only concurrency errors that happen since the redisplay of the Edit page will be caught.
                        departmentToUpdate.RowVersion = databaseValues.RowVersion;
                    }
                }
                catch (RetryLimitExceededException ex)
                {
                    //Log the error (uncomment dex variable name and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
            ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(View(departmentToUpdate));
        }
 public async Task Update(Student obj)
 {
     _students.Attach(obj);
     _context.Entry(obj).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
 public async Task Update(T obj)
 {
     table.Attach(obj);
     _context.Entry(obj).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
 public void Update(T entity)
 {
     _DbSet.Attach(entity);
     _schoolDBContext.Entry(entity).State = EntityState.Modified;
 }