[英]Entity Framework Code First - Add Child Entity to Parent by Primary Key
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? 在Entity Framework Code First CTP5中,是否可以仅使用子级的主键将子级实体添加到父级实体集合中? 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 (ie without loading any entities at all)? 对于奖励积分,是否可以仅使用父子主键(即根本不加载任何实体)来完成?
Compiled in my head against CTP4 so be aware. 反对CTP4在我的脑海中编译,因此请注意。
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. 您需要先调用SaveChanges,然后才能持久保存任何内容。
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. 仅使用ID附加和实体并与Statemanager一起使用在EF中效果很好,并允许您在性能方面创建一些非常好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.