简体   繁体   English

无法使用实体框架保存记录

[英]Can't save record using Entity Framework

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 System.Data.Entity.dll中发生了类型为'System.InvalidOperationException'的未处理异常

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker. 附加信息:IEntityChangeTracker的多个实例不能引用一个实体对象。

Edit 2 : 编辑2

Code to show my function getPaitnetByPatineyNewId 显示我的函数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;
    }

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 我认为您在DAL中的关注点分离方面存在一些问题,但是对于简短的解决方案,如果是新实体,则仅应添加(而不是附加)

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);
}

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. 我在窗体isUpdate上放置了一个标志,并在“保存”按钮上进行了检查,然后检查是否类似于下面的保存调用,然后添加仅调用savechanges及其现在正在工作,谢谢大家的帮助,希望对您有所帮助。

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM