开发者

How can I associate a new entity with an existing entity in EF4?

I've got a Patient entity (storing up-to-date information about a patient) and a TreatmentPlanPatient entity (a copy of a patient's date as it was when the "treatment plan", another entity not relevant to this question, was created):

How can I associate a new entity with an existing entity in EF4?

I'm using Table-per-Type in this case. Now when I try to add a new TreatmentPlanPatient that's pointing to the Patient it was created from, EF4 actually does this:

  1. It retrieves the existing patient from the database
  2. Creates a copy of that patient
  3. Assigns it a new ID GUID (despite StoreGeneratedPattern = None!)
  4. Inserts the new patient into the Patients table
  5. Rewrites the ID in my TreatmentPlanPatient instance to point to this new Patient
  6. Inserts the new treatment plan patient in to the TreatmentPlanPatients table.

This is my开发者_StackOverflow社区 code causing above behavior:

using(var container = new SmartTherapyContainer()) {

  // Look up the patient in the current container to make sure EF4 recognizes it
  var patient = container.Patients.First(r => r.Id == selectedPatient.Id);

  var treatmentPlanPatient = new TreatmentPlanPatient() {
    Id = Guid.NewGuid(),
    FirstName = patient.FirstName,
    LastName = patient.LastName,
    Street = patient.Street,
    ZipCode = patient.ZipCode,
    City = patient.City,
    BirthDate = patient.BirthDate,
    Telephone = patient.Telephone,
    Email = patient.Email,
    ClonedPatient = patient
  };

  // EF4 doesn't generate a separate .TreatmentPlanPatients collection :-/
  container.Patients.AddObject(treatmentPlanPatient);
  container.SaveChanges();

}

What is going on? How can I get EF4 to just insert a treatment plan patient into the TreatmentPlanPatients table and associate it with the existing patient in the Patients table?


I am not sure I completely understand what you are trying to do but according to your schema, the Patient table is a parent of TreatmentPlanPatients table (one to many relationship). Hence, you should add the TreatmentPlan to the Patient itself and not the Patients table. So rather than doing container.Patients.AddObject(treatmentPlanPatient), you should do patient.TreatmentPlanPatients.Add(treatmentPlanPatient). In this case, TreatmentPlanPatients should be a navigational property on the Patient table/entity.

OR, if you really want to use inheritance, then you have to use the same primary key (Id in this case) in both tables and have a one-to-one relationship.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜