如何插入子实体? [英] How to insert a child entity?

查看:96
本文介绍了如何插入子实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个EF应用程序并遇到以下场景,我有一个父实体,它有一个或多个子实体。表示层(asp.net web app)调用服务层InsertChild(Child child,int parentId),服务层内的代码首先必须选择找到正确的Parent实体,以便将它与child.Parent相关联,我可以将它添加到上下文中。我有一种感觉,我是以迂回的方式做这件事,让我按照正确的方式来做这件事。我觉得我可以将服务层中的签名保存到InsertChild(Child子)而不必传递parentId,但不知道如何将其与父级关联,其方式是上下文将识别它正在添加一个孩子到现有的父母。

谢谢!

I am writing my first EF application and ran into the following scenario, I have a Parent entity that has one or more Children entities.  The presentation layer (asp.net web app) calls the service layer InsertChild(Child child, int parentId) and the code inside service layer first has to select to find the right Parent entity in order to associate it with child.Parent, only then can I add it to the context.  I have a feeling that I am doing it in a roundabout way, school me on the proper way of doing this.  I feel that I might be able to keep my signature in the service layer to InsertChild(Child child) without having to pass the parentId, but not sure how to associate it to the parent in a way where the context will recognize that it's adding a child to an existing parent.

Thanks!

推荐答案

如果你有父母身份有避免获取父元素和建立关系的两种方法。第一种方法是使用EntityKey将EntityReference设置为父元素。你可以在我写的帖子中读到这种方式: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/05/15/setting-an-entityreference-using-an-entitykey-in-实体framework.aspx 。执行此操作后,SaveChanges将更新子级和父级之间的引用。

第二种选择是对父级使用存根实体,该父级是部分填充的实体。使用存根实体可以帮助您避免使用EntityKey,这是我建议的第一个解决方案。您可以在Alex James写的帖子中阅读有关使用存根实体的更多信息: http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using- stub-entities.aspx

我希望它会对你有所帮助。

Hi,
If you have the parent ID There are two ways to avoid getting the parent element and to make the relation.

The first way is to set the EntityReference to the parent using an EntityKey. You can read about this way in a post I wrote: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/05/15/setting-an-entityreference-using-an-entitykey-in-entity-framework.aspx. After you do so doing SaveChanges will update the reference between child and parent.

The second option is to use a stub entity for the parent which is a partially populated entity. Using stub entities can help you to aviod the use of EntityKey which is exaplain in the first solution I suggested. You can read more about using stub entities in a post that Alex James wrote: http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx

I hope it will help you.


这篇关于如何插入子实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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