实体框架插入多个外键

时间:2010-08-10 13:45:53

标签: c# entity-framework

Patient.DivHospitalID (FK)
DivHospital.HospitalID (FK)
Hospital.HospitalID (PK)

我需要将医院插入DivHospital并将其链接/插入患者DivHospital。

Patient tp = new Patient();
DivHospital dh = new DivHospital();

dh.HospitalReference.EntityKey =
     new EntityKey("transportPagerEntities.Hospital", "hospitalID", hospital);
         tp.DivHospitalReference.EntityKey = new  
         EntityKey("transportPagerEntities.DivHospital", "divHospitalID", hospitalref);

context.AddToDivHospital(dh);
context.AddToTransportPatient(tp);
context.SaveChanges();

2 个答案:

答案 0 :(得分:1)

假设您没有处理PK(int),并且因为您使用的是ORM,那么您不应该这样做。

您不需要执行EntityKey,只需直接设置它们即可。

Patient tp = new Patient();
DivHospital dh = new DivHospital();

dh.Hospital = hospital;
tp.DivHospital = hospitalref;

context.AddToDivHospital(dh);
context.AddToTransportPatient(tp);

context.SaveChanges();

答案 1 :(得分:1)

使用EntityFramework这很容易(如果我理解你的问题):

Patient tp = new Patient();
DivHospital dh = new DivHospital();

dh.Patient.Add(tp);  //magic

context.AddToDivHospital(dh);
context.SaveChanges();