Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not Saving Changes #42

Open
mglodack opened this issue Jul 15, 2016 · 7 comments
Open

Not Saving Changes #42

mglodack opened this issue Jul 15, 2016 · 7 comments

Comments

@mglodack
Copy link

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 😕

Am I going about this the wrong way?

@jonny-novikov
Copy link

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
Copy link
Author

mglodack commented Jul 18, 2016

@jonny-novikov Awesome!

Thank you for the explanation and SO reference. 😄

@mglodack
Copy link
Author

@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
Copy link
Contributor

tiesont commented Jul 18, 2016

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
Copy link

goBazinga commented Oct 12, 2016

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
Copy link

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
Copy link
Contributor

tiesont commented Jan 3, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants