Code Monkey home page Code Monkey logo

Comments (7)

tiesont avatar tiesont commented on August 16, 2024 1

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.

from dbcontextscope.

jonny-novikov avatar jonny-novikov commented on August 16, 2024

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

from dbcontextscope.

mglodack avatar mglodack commented on August 16, 2024

@jonny-novikov Awesome!

Thank you for the explanation and SO reference. 😄

from dbcontextscope.

mglodack avatar mglodack commented on August 16, 2024

@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
}

from dbcontextscope.

goBazinga avatar goBazinga commented on August 16, 2024

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.

from dbcontextscope.

davidbuckleyni avatar davidbuckleyni commented on August 16, 2024

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

from dbcontextscope.

tiesont avatar tiesont commented on August 16, 2024

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

from dbcontextscope.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.