locked
Entity will add record to database but it will not update it. RRS feed

  • Question

  • User-1868255333 posted

    Context is not saving to the database no matter what i do it will insert a new record fine but not save

        private void btnOk_Click(object sender, EventArgs e)
    
    	{
    
    		
    
    		  SourceContext SourceDal = new SourceContext();
    
    
    
    		Appointment _appointment = new Appointment();
    
    		int errorCount = 0;
    
    
    
    		Patient _patient = new Patient();
    
    		_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);
    
    		_patient.SSN = txtSSN.Text;
    
    
    
    		_patient.FirstName = txtPatientFirstName.Text;
    
    		_patient.LastName = txtPatientLastName.Text;
    
    		_patient.Middle = txtPatientMiddle.Text;
    
    		_patient.AddressOne = txtPatientAddressOne.Text;
    
    		_patient.City = txtPatientCity.Text;
    
    		_patient.State = txtPatientState.Text;
    
    		_patient.ZipCode = txtPatientZip.Text;
    
    
    
    
    
    		_patient.HomePhone = txtPatientHomePhone.Text;
    
    		_patient.WorkPhone = txtPatientWorkPhone.Text;
    
    		_patient.CellPhone = txtPatientCellPhone.Text;
    
    
    
    		if (rBtnHomePhone.Checked == true)
    
    			_patient.ApptPhone = txtPatientHomePhone.Text;
    
    		if (rBtnHomePhone.Checked == true)
    
    			_patient.ApptPhone = txtPatientHomePhone.Text;
    
    		if (rBtnWorkPhone.Checked == true)
    
    			_patient.ApptPhone = txtPatientWorkPhone.Text;
    
    
    
    
    
    		_patient.BirthDate = dtBirthDate.DateTime;
    
    		_patient.emailAddress = txtPatientEmail.Text;
    
    		_patient.Race = (int)dpRace.SelectedValue;
    
    		_patient.Ethnicity = (int)dpEthnicity.SelectedValue;
    
    		_patient.Language = (int)dpLanguages.SelectedValue;
    
    
    
    		_patient.AlertNote = txtPatientNotes.Text;
    
    
    
    
    
    		if (dpGender.Text == "")
    
    		{
    
    			dpGender.Focus();
    
    			errorCount = 1;
    
    			lblGenderRequired.Text = "* Gender is required.";
    
    
    
    		}
    
    		else
    
    		{
    
    			errorCount = 0;
    
    			lblGenderRequired.Visible = false;
    
    		}
    
    		_patient.Gender = dpGender.Text.Substring(0, 1);
    
    
    
    
    
    
    
    
    
    		_patient.PatientID = txtPatientId.Text;
    
    		txtPatientFirstName.Text = _patient.FirstName;
    
    		txtPatientLastName.Text = _patient.LastName;
    
    		// IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.                
    
    			SourceDal.AddToPatient(_patient);
    
        }
    
    

    Add to paitent has the following

        public void AddToPatient(Patient newPatient)
    
            {
    
                using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
    
                {
    
                    myContext.Patients.Add(newPatient);
    
    
    
                    if (newPatient.ID == 0)
    
                    {
    
                        myContext.Entry(newPatient).State = EntityState.Added;
    
                    }
    
                    else
    
                    {
    
                        myContext.Entry(newPatient).State = EntityState.Modified;
    
                    }
    
                    try
    
                    {
    
                        myContext.SaveChanges();
    
                    }
    
    
    
                    catch (DbEntityValidationException ex)
    
                    {
    
                        foreach (var entityValidationErrors in ex.EntityValidationErrors)
    
                        {
    
                            foreach (var validationError in entityValidationErrors.ValidationErrors)
    
                            {
    
                                Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
    
                            }
    
                        }
    
    
    
                    }
    
                }
    
            }
    
    

    It adds in the record fine but it just wont save the current record no matter what i do even though all the details are correct. But when i reload the form and the application the update is not there the email address is not saved no are any the other updates.

    Wednesday, January 3, 2018 8:56 PM

All replies

  • User475983607 posted

    Have you tried simply using the debugger to step through the code? 

    https://msdn.microsoft.com/en-us/library/y740d9d3.aspx

    As written the code base hides errors that are not DbEntityValidationException types.  If you are not using the debugger, you might be missing an error or two.  Also there is no validation on the txtPatientId.Text property.  Are you sure the textbox has a value?

    Wednesday, January 3, 2018 9:25 PM
  • User1120430333 posted

    Your code is not optimal. The add and the update should be two separate methods.

    Secondly, in order to update the object and persist it to the database, you must get the object first, update it, change the state and then save it.

    http://www.entityframeworktutorial.net/EntityFramework4.3/update-entity-using-dbcontext.aspx

     public void CreateStudent(DTOStudent dto)
            {
                using (var context = new CUDataEntities())
                {
                    var student = new Student
                    {
                        FirstName = dto.FirstName,
                        LastName = dto.LastName,
                        EnrollmentDate = dto.EnrollmentDate
                    };
    
                    context.Students.Add(student);
                    context.SaveChanges();
                }
            }
    ----------------------------------------------------------
    
      public void UpdateStudent(DTOStudent dto)
            {
                var student = new Student();
    
                using (var context = new CUDataEntities())
                {
                    student = (context.Students.Where(a => a.StudentID == dto.StudentID)).SingleOrDefault();
                }
    
                if (student != null)
                {
                    student.FirstName = dto.FirstName;
                    student.LastName = dto.LastName;
                    student.EnrollmentDate = dto.EnrollmentDate;
                } 
    
                using (var dbcontext = new CUDataEntities())
                {
                    if (student != null)
                    {
                        dbcontext.Entry(student).State = EntityState.Modified;
                        dbcontext.SaveChanges();
                    }
                }
            }
        }
    Wednesday, January 3, 2018 10:46 PM
  • User-1838255255 posted

    Hi david40nib,

    According to your description, i think you need execute the save change method after add method when you insert the record to the dbcontext! Please check the following tutorials:

    Add New Entity using DBContext in Disconnected Scenario:

    http://www.entityframeworktutorial.net/EntityFramework4.3/add-entity-using-dbcontext.aspx 

    Entity Framework Add and Attach and Entity States: 

    https://msdn.microsoft.com/en-us/library/jj592676%28v=vs.113%29.aspx?f=255&MSPPError=-2147217396 

    If still not work, please check this tutorial about how to debug code:

    https://msdn.microsoft.com/en-us/library/y740d9d3.aspx 

    Best Regards,

    Eric Du 

    Thursday, January 4, 2018 8:41 AM