分离实体以及引用的实体 [英] Detaching entity along with referenced entities

查看:58
本文介绍了分离实体以及引用的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我打算使用Entity Framework开发一个项目。在我开始实施它之前尝试进行一些研发时,我发现了这个问题,希望某些人能帮助我找到解决方案。

Ok, I am planning to develop a project using Entity Framework. While i was trying to do some R&D before i kick off implementing it, I found this problem, hope some of you people help me find a solution to it.

我有一个名为 Person的实体,引用了具有一对多(1:N)关系的 Members实体。任务是查询Person实体及其对应的Members集合,并将其传递到表示层以对其进行查看,修改或删除,然后将修改后的实体对象传递回Model层以将该实体附加到上下文并将其保存到数据库中。

I have a entity named 'Person' referenced with 'Members' entity with one to many (1:N) relationship. The task would be to query Person entity along with its corresponding Members collection and pass it to the presentation layer to view, modify or delete over it and then the modified entity object will be passed back to the Model layer to attach the entity to the context and save it to the DB.

据我分离/附加wrt像个人这样的单一实体,并将其保存到数据库中,一切正常。
但是,当我尝试用其引用的实体(成员)查询实体(人)并分离时,可以将其发送到表示层。我发现仅获得了Person实体集合,并且从上下文分离了参考成员实体集合后,该参考成员集合被完全删除。

As far as I Detach/Attach w.r.t. a single entity like 'Person' and save it to the DB every thing works absolutely fine. But, when i try to query an entity (Person) with its referenced entity (Member) and detach so that i can send it to the presentation layer. I find that I get only Person entity collection and the reference Member entity collection is totally removed after detaching it from the context.

在这里,我粘贴我的代码片段以供参考:

Here I am pasting my code snippet for reference:

using (GOLProfessionalEntities context = new GOLProfessionalEntities())
{
     ObjectQuery<Person> query =
        context.Person.Include("Members");

     var person = query.First();
     context.Detach(person);

     return person;
}

如果有人提出解决方案,我将非常高兴。

I would be really delighted if some one comes out with a solution to this.

预先感谢。
-ssak32

Thanks in advance. -ssak32

推荐答案

您可以将ObjectQuery上的MergeOption设置为NoTracking。这样,Person不会首先附加到ObjectContext。

You could set MergeOption on ObjectQuery to NoTracking. This way Person will not be attached to the ObjectContext in the first place.

            using (GOLProfessionalEntities context = new GOLProfessionalEntities())
            {
                ObjectQuery<Person> query =
                   context.Person.Include("Members");
                query.MergeOption = MergeOption.NoTracking;// <--

                var person = query.First();

                return person;
            }

答案太晚了,可能会对某人有所帮助。

I'm so late with the answer by it might help someone.

这篇关于分离实体以及引用的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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