how add entityobject with exsist object that have relational in Entity framework
my scenario
i want to create application for dental clinic . I have vs2010 ultimate and first time started with empty model and then I crate it with Generate database from model…… now I have afew class which some of this makes paritial by me because to extend flexible I have class with name patient and doctor that derived from Person abstract class Each person have 0..1 relation with patientcase .Each doctor have many patient and each patient have exactly 1 doctor (or relation with doctor).In other side each patientcase hold insurance info and each insuranceinfo have relation with insurancecompany class now in my pritial class with name patient I;m try to create new patient with this constructor : Attention: new doctor and new insurance company exsist before and saved in database) And selectdoctor is variable with type doctor that hold select doctor from combobox.
public Patient(Doctor doctorname, string n, string f, string codemeli, string datebirth, bool gender, bool material, string age, bool group,PatientCase pc,Address a,contactdetail condetail)
{
Doctorname.patient.add(this); // is this code right?
selectdoctor = doctorname;
this.Firstname = n;
this.lastname = n;
this.internationalcode = codemeli;
this.dateofbirth = datebirth;
this.gender = gender;
this.materialstatus = material;
if(age!="")
this.age = int.Parse(age);
this.group = group;
this.PatientCase = pc;
this.adres = a;
this.contac = condetail;
}
And its my save method for save patient in this class:
public void save()
{
db = new DentalContainer(DbAccess.Get_EntityConstring());
dr.Patient.Add(this);
db.tblPerson.AddObject(this);
db.SaveChanges();
}
And it's code from addpatient form to ma开发者_C百科ke new patient:
Patient newpatient=new Patient (SelectDoctor,txtname.Text,txtfamily.Text,txtinternationalcode.Text,txtbirthdate.Text,get_GenderStatus(chkMan.Checked,chkWoman.Checked),get_MaterialStatus(chkunmarried.Checked,chkmarried.Checked),txtage.Text,get_group(chkMan.Checked,chkadult.Checked),npc,newaddress ,newcontacdetail);
Npc is patientcase which I create it earlyier in code above; and the pass it to patient constructor now when db.savechanges is occur this exception or error is shown: The EntityKey
property can only be set when the current value of the property is null.
Where is my mistake help me please?
(i) your constructor shouldn't add the patient to a doctor, it should just construct a Patient disconnected from any object graph (side effects in constructors are a bad idea).
(ii) you only need to connect objects to an object graph once: construct a patient and then add it to a doctor's .Patient collection, then save changes. Don't add it to the person table too.
(iii) your pluralization and table naming could be clearer - it should be dr.Patients
and db.People
.
精彩评论