开发者

Why we need to attach a selftracking entity to context before deleting?

开发者 https://www.devze.com 2023-01-11 00:35 出处:网络
I have a service which will add , update and delete a patient entity . I made the patient entity is selftracking entity .

I have a service which will add , update and delete a patient entity . I made the patient entity is selftracking entity .

But only for delete i need to call 'Attach' the entity before deleting , why not attach required for add and update .

What is the logic behind attaching only for delete ( I have cascading property = true)

 public List<Patient> AddPatient(Patient pat)
    {


        DataBaseCon开发者_JAVA百科text.Patients.AddObject(pat);           
        DataBaseContext.SaveChanges();
        return DataBaseContext.Patients.Include("PatientContacts").ToList();

    }

    public List<Patient> DeletePatient(Patient pat)
    {

       //Why only for delete we need to attach ??????????

        DataBaseContext.Patients.Attach(pat);
        DataBaseContext.Patients.DeleteObject(pat);
        DataBaseContext.SaveChanges();
        return DataBaseContext.Patients.Include("PatientContacts").ToList();
    }

    public List<Patient> UpdatePatient(Patient pat)
    {

         DataBaseContext.Patients.ApplyChanges(pat);
         DataBaseContext.SaveChanges();
         return DataBaseContext.Patients.Include("PatientContacts").ToList();
    }


you should send the patientGUID to the method and then get the patient from the db and then do a delete

public List<Patient> DeletePatient(string patientGUID)
{

   var patient = DataBaseContent.Patients.SingleOrDefault(p => p.patientGUID == patientGUID);

    DataBaseContext.Patients.DeleteObject(patient);
    DataBaseContext.SaveChanges();
    return DataBaseContext.Patients.Include("PatientContacts").ToList();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号