1

My objects will not save no matter what I do they will fetch and get info and make a new record but not update.

This is the code that details with getting existing patient and then modifying the record setting the state then calling save change this is cracking my head the last three hours what is going wrong. I was told you had to change the entity state of an object before it would no if to save but when i try to attach it it says its already attached

Appointment _appointment = new Appointment();
int errorCount = 0;

Patient _patient = SourceDal.getPatientByPatientNewId(Convert.ToInt32(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 =   Convert.ToInt32(dpRace.SelectedValue);
_patient.Ethnicity =Convert.ToInt32(dpEthnicity.SelectedValue);
_patient.Language =  Convert.ToInt32(dpLanguages.SelectedValue);

if (dpGender.Text == "")
{
    dpGender.Focus();
    errorCount = 1;
    lblGenderRequired.Text = "* Gender is required.";
}
else
{
    errorCount = 0;
    lblGenderRequired.Visible = false;
}

_patient.Gender = "M";
_patient.PatientID = txtPatientId.Text;

SourceDal.SourceEntities.Patients.Attach(_patient);
SourceDal.SourceEntities.Patients.Context.ObjectStateManager.ChangeObjectState(_patient, EntityState.Modified);
SourceDal.SourceEntities.SaveChanges();

The error I get is

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Edit 2:

Code to show my function getPaitnetByPatineyNewId

    public Patient getPatientByPatientNewId(int newId)
    {
        Patient patient = new Patient();

        if (newId == -1)
        {
            patient = new Patient();
        }
        else
        {
            patient = SourceEntities.Patients
                                    .Where(w => w.ID == newId)
                                    .FirstOrDefault();
        }

        return patient;
    }
10
  • Are you using EF6? Commented Jan 4, 2018 at 1:30
  • 1
    @yuyangJian EF5 Commented Jan 4, 2018 at 1:31
  • 1
    @yuyangJian project reasons cant upgrade so have to go with it Commented Jan 4, 2018 at 1:31
  • @davidbuc your entity is already attached to the context (you're getting it and not removing it, or not using AsNoTracking, so EF keeps track of it). That's why you can't attach it. Commented Jan 4, 2018 at 1:31
  • @ESG thanks for the quick answer could you provide a solution as to what i might do to solve this . Commented Jan 4, 2018 at 1:32

2 Answers 2

2

I think you have some issues with proper separation of concerns within your DAL, but for the short solution, you should only add (and not attach) if it's a new entity

if (_patent.PatentId == 0)
{
    _patient.PatientID = txtPatientId.Text; // If you're using an identity column, remove this line. I would also strongly suggest not letting the user change this...
    SourceDal.SourceEntities.Patients.Add(_patient);
}
Sign up to request clarification or add additional context in comments.

6 Comments

But how do i tell it if its changed as calling save changes is not updating the record ?.
New entities should be added, not attached. For existing entities, EF tracks all those changes to object properties so you should not have to do anything special, unless change tracking is actively disabled, in which case you have another problem on your hands
I am using ef5 how would one check that
It would be the Context.Configuration.AutoDetectChangesEnabled property (defaults to true)
I keep seeing i have to use this to force entry.State = EntityState.Modified; the state how would i use that in the above thougyh
|
0

For Anyone else the above scenarios did not work for me so this is what I had to do. I put a flag on my forms isUpdate and check that on the save button then if save call similar to below then if add just call savechanges and its now working thank you for everyone help hope this help someone.

public void SaveProviders(Provider _providers)
{
  try
    {


            using (var ctx = new SMBASchedulerEntities(this.Connectionstring))
            {
                ctx.Providers.Add(_providers);
                ctx.Entry(_providers).State = System.Data.Entity.EntityState.Modified;
                ctx.SaveChanges();
            }
        }


        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }

    }

1 Comment

Generally if you want to check your model is valid before sending it to the DB (and throwing errors) you can just call DbContext.GetValidationErrors() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.