Entity Framework Code First - Add Child Entity to Parent by Primary Key
In Entity Framew开发者_StackOverflow社区ork Code First CTP5 is it possible to add a child entity to a parent entity collection using only the primary key of the child? My goal is to avoid having to first load the child entity from the data store.
For bonus points, can this be accomplished using only the parent and child primary keys (i.e. without loading any entities at all)?
Compiled in my head against CTP4 so be aware.
public void AddPersonToList(int id, int toAdd)
{
var mailList = new MailList { ID = id, ContactInformations = new List<ContactInformation>() };
this.db.MailLists.Attach(mailList);
var ci = new ContactInformation { ID = toAdd };
this.db.ContactInformations.Attach(ci);
this.db.ObjectStateManager.ChangeRelationshipState(mailList, ci, ml => ml.ContactInformations, System.Data.EntityState.Added);
}
You need to call a SaveChanges before anything is persisted.
Attaching and entity with only a ID and working with the Statemanager works really well in EF and allows you to create some really nice solutions performance wise.
精彩评论