实体框架code首先 - 添加子实体于母公司按主键 [英] Entity Framework Code First - Add Child Entity to Parent by Primary Key

查看:174
本文介绍了实体框架code首先 - 添加子实体于母公司按主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实体框架code首先CTP5是有可能子实体添加到使用孩子只有主键父实体集合?我的目标是避免必须首先从数据存储加载子实体

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)?

推荐答案

在编译我的头CTP4所以要知道。

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);

}

您需要调用的SaveChanges任何被持久化之前。

You need to call a SaveChanges before anything is persisted.

安装和实体只有一个ID,并与StateManager的工作确实很好的EF和允许你创建一些非常好的解决方案的性能明智的。

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.

这篇关于实体框架code首先 - 添加子实体于母公司按主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆