I am new to the Entity Framework and am looking for some direction on creating the relationships between an entity and related many-to-many associative entities and inserting them in one operation.
The relevant entities in my EDMX:
Participant
ID
Name
ParticipantCustomField
ParticipantID
CustomFieldID
Value
CustomField
ID
Name
I need to insert a single Participant
entity and many ParticipantCustomField
entities. The related CustomField
entity will already be in the database at the time of insert.
I have a repository create method which accepts a Participant
and a collection of ParticipantCustomField
objects:
public Participant CreateParticipant(Participant participant, List<ParticipantCustomField> customFields)
{
// need to establish relationship here
entities.AddToParticipant(participant);
entities.SaveChanges();
return participant;
}
I have tried several methods but cannot figure out how to properly relate the collection of ParticipantCustomField
objects with the new Participant
before the insert. I know the CustomFieldID
foreign key as that is set outside of this method, but the ParticipantID
foreign key cannot be set until the Participant
is inserted.
I guess since this is the Entity Framework I shouldn't be focused on "foreign keys", which I think are only there because my associative table has a third column, but on relations.
Thanks for any help!