Entity Framework: Creating and inserting many to many relationships

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!


You don't need to set ParticipantCustomField.ParticipantId . The framework will do that for you. Instead you'd do something like:

foreach (var cf in customField)
{
    participant.CustomFields.Add(cf);
}
entities.AddToParticipant(participant);
entities.SaveChanges();
return participant;

I'm making some presumptions about your mappings here, but this should give you the general idea.

链接地址: http://www.djcxy.com/p/37470.html

上一篇: 实体框架:关联具有可空字段的实体的问题

下一篇: 实体框架:创建并插入多对多关系