C# 如何将entityobject添加到实体框架中具有关系的现有对象中

C# 如何将entityobject添加到实体框架中具有关系的现有对象中,c#,entity-framework,C#,Entity Framework,我的情景 我想为牙科诊所创建应用程序。我有vs2010终极版,第一次从空模型开始,然后用模型生成数据库将其装箱…… 现在我有了一个新的类,其中一些类对我来说很重要,因为它扩展了灵活性 我有一个名为patient和doctor的类,它是从Person抽象类派生的 每个人与病人的关系为0..1。每个医生有许多病人,每个病人正好有一个医生(或与医生的关系) 在另一边,每个patientcase持有保险信息,每个insuranceinfo都与我的pritial类中名为patient I的insuranc

我的情景
我想为牙科诊所创建应用程序。我有vs2010终极版,第一次从空模型开始,然后用模型生成数据库将其装箱…… 现在我有了一个新的类,其中一些类对我来说很重要,因为它扩展了灵活性 我有一个名为patient和doctor的类,它是从Person抽象类派生的 每个人与病人的关系为0..1。每个医生有许多病人,每个病人正好有一个医生(或与医生的关系)

在另一边,每个patientcase持有保险信息,每个insuranceinfo都与我的pritial类中名为patient I的insurancecompany类有关系;m尝试使用此构造函数创建新患者: 注意:新医生和新保险公司之前存在,并保存在数据库中) selectdoctor是带有类型doctor的变量,该类型的doctor包含从组合框中选择医生

  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;

  }
在这个类中,它是我用于保存患者的保存方法:

   public void save()
   {
       db = new DentalContainer(DbAccess.Get_EntityConstring());
       dr.Patient.Add(this);
       db.tblPerson.AddObject(this);
       db.SaveChanges();
   }
这是来自addpatient表单的代码,用于创建新患者:

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是我在上面代码中较早创建的patientcase;当发生db.savechanges时,立即将其传递给患者构造函数。将显示此异常或错误:
EntityKey
属性的当前值为null时才能设置

我的错误在哪里请帮帮我?

(i)你的构造器不应该将患者添加到医生,它应该只构造一个与任何对象图断开连接的患者(构造器中的副作用是个坏主意)

(ii)只需将对象连接到对象图一次:构造一个患者,然后将其添加到医生的.patient集合,然后保存更改。也不要将其添加到person表中

(iii)您的多元化和表格命名可能更清晰-应该是
dr.Patients
db.People