mehdime / DbContextScope

A simple and flexible way to manage your Entity Framework DbContext instances
http://mehdi.me/ambient-dbcontext-in-ef6/
MIT License
631 stars 273 forks source link

Not Saving Changes #42

Open mglodack opened 8 years ago

mglodack commented 8 years ago

I feel like I'm doing this wrong, but for some reason I can't seem to SaveChanges properly.

using (var dbContextScope = _dbContextScopeFactory.Create())
{
    var context = dbContextScope.DbContexts.Get<ApplicationContext>();

    var file = context.Set<Models.File>().Find(id);

    file.Name = "This should be updated, but it's not :)";

    var result = dbContextScope.SaveChanges();
}

The only way I'm able to actually get the result to be > 0 is to create one of these _dbContextScopeFactory.CreateWithTransaction(IsolationLevel.Serializable)

My creates work perfectly, but for some reason the updates don't seem to update :confused:

Am I going about this the wrong way?

jonny-novikov commented 8 years ago

Hi, @mglodack Actually assigning field and calling SaveChanges() shouldn't change anything. You can write somethink like this:

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

Be careful because in other cases entity can be detached from context and you should call:

   context.Set<Models.File>.Attach(file);

So, I use the general function with Generic Repository pattern aka:

    public void Update(TEntity entity)
    {
        Entities.Attach(entity); // Entities => DbContext.Set<TEntity>
        DbContext.Entry(entity).State = EntityState.Modified;
    }

Also take a look at this answer at SO http://stackoverflow.com/questions/30987806/dbset-attachentity-vs-dbcontext-entryentity-state-entitystate-modified

mglodack commented 8 years ago

@jonny-novikov Awesome!

Thank you for the explanation and SO reference. :smile:

mglodack commented 8 years ago

@jonny-novikov

I'm still not seeing any changes being saved when I call the DbContextScope SaveChanges method.

However, if I call the actual context SaveChanges method then the records get updated.

I was under the impression that I no longer need to call DbContext SaveChanges.

Is this still true or am I misunderstanding the library?

using (var dbContextScope = _dbContextScopeFactory.Create())
{
   // Make changes
  dbContextScope.SaveChanges(); // Should call all the DbContext instances SaveChanges methods
}
tiesont commented 8 years ago

Is this code nested within another scope? If so, SaveChanges() will not actually do anything (the wrapping scope will commit any outstanding changes when it's disposed).

I assume the above is a long shot, but it is worth eliminating as a potential cause.

goBazinga commented 7 years ago

I've got the same issue in case of updating multiple records. I've got more than one row to update, I loop through, attach each entity and then call savechanges on dbcontextscope at the end. as soon as it tries to add another row, attaching entity throws primary key error. But this works fine if I call the dbcontext.savechanges() s So, dbContextScope.SaveChanges(); doesn't work. dbContextScope.DbContexts.Get<>().SaveChanges(); Works.

davidbuckleyni commented 6 years ago

I am having an issue sql sever will not update the object

` 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.Patients.Attach(newPatient);
                myContext.Entry(newPatient).State = EntityState.Modified;
            }
            try
            {
                myContext.SaveChanges();
            }

            catch (Exception ex)
            {

            }
        }
    }

This is where i am calling it from ` private void btnOk_Click(object sender, EventArgs e) { 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);

        if (errorCount > 0)
        {
            DialogResult result = DialogResult.Cancel;

            result = MessageBox.Show("Please check required fields and complete", "Validation Errors", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        }
        else
        {
            DialogResult result = DialogResult.Cancel;

            result = MessageBox.Show("Patient has been saved", "Record Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        }
    }

It will add my record ok but not save

tiesont commented 6 years ago

@davidbuckleyni What does any of that have to do with DbContextScope?