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):
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:
- It retrieves the existing patient from the database
- Creates a copy of that patient
- Assigns it a new ID GUID (despite StoreGeneratedPattern = None!)
- Inserts the new patient into the
Patients
table - Rewrites the ID in my
TreatmentPlanPatient
instance to point to this new Patient - 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.
精彩评论