Entity Framework Code First - Add Child Entity to Parent by Primary Key

梦想与她 提交于 2019-12-11 07:02:13

问题


In Entity Framework 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)?


回答1:


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.



来源:https://stackoverflow.com/questions/5264720/entity-framework-code-first-add-child-entity-to-parent-by-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!