简体   繁体   English

实体框架代码优先-通过主键将子实体添加到父实体

[英]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.

相关问题 实体框架代码首先是多层父子外键 - Entity Framework code first multiple tier parent child foreign key 在实体框架中,在父实体中加载子级(非主键关联) - In Entity framework load child in parent entity (non primary key association) 违反主要密钥实体框架代码 - Violation of primary key Entity Framework Code First 首先删除实体框架代码中的主键 - deleting primary key in entity framework code first 实体框架-代码优先-没有共享主键时的实体拆分 - Entity Framework - Code First - Entity Splitting When There Is No Shared Primary Key 实体框架:父和子主键具有相同名称的继承 - Entity Framework: Inheritance with same name for parent and child primary key 实体框架代码优先 - 非主键字段的外键 - Entity Framework Code First - Foreign Key to non primary key field 实体框架外键作为主键代码优先 - Entity Framework Foreign Key as Primary Key Code First 如何在Entity Framework Code First中使用字符串主键延迟加载子对象? - How to Lazy Load child object with string primary key in Entity Framework Code First? 代码生成:向实体框架添加主键/外键 - Code Generation : Add primary key / foreign key to Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM