开发者

Entity Framework Insert multiple foreign keys

开发者 https://www.devze.com 2023-01-10 19:00 出处:网络
Patient.DivHospitalID (FK) DivHospital.HospitalID (FK) Hospital.HospitalID (PK) I need to insert into DivHospital the Hospital and link/insert into Patient the DivHospital.
Patient.DivHospitalID (FK)
DivHospital.HospitalID (FK)
Hospital.HospitalID (PK)

I need to insert into DivHospital the Hospital and link/insert into Patient the DivHospital.

Patient tp = new Patient();
DivHospital dh = new Div开发者_运维技巧Hospital();

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


Assuming you aren't dealing with PKs (ints) and since you are using an ORM you shouldn't be.

You don't need to do the EntityKey stuff, just set them directly.

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

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

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

context.SaveChanges();


With EntityFramework this is really easy (if I understand your problem):

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

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

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

精彩评论

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