从数据库中选择浅对象,从外键中删除所有引用 [英] Select shallow object from database, dropping all references from foreign keys

查看:53
本文介绍了从数据库中选择浅对象,从外键中删除所有引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我经常从数据库中获取一些数据,将其自动序列化,然后将其发送到某个地方.

In my app, I frequently fetch some data from database, serialize it automatically and then send it somewhere.

数据库结构非常复杂,但让我们假设我有三个关系,A,B和C,其中B和C具有指向A的外键.因此,可以使用Navigation Properties(而且我喜欢这个功能,我不想禁用它.

Database structure is quite complicated, but let's assume, that I have three relations, A, B and C, where B and C have foreign keys pointing to A. Thus, it is possible to navigate between these relations using Navigation Properties (and I like this feature, I don't want to disable it).

数据获取是通过Entity Framework完成的,所以我只是从一些ObjectContext中限制它.设置了一个MergeOptions.NoTracking选项.

Data fetching is done with Entity Framework, so I just linq it from some ObjectContext. There is a MergeOptions.NoTracking option set.

我的数据序列化检查每个属性,并以指定的方式保存它.我不想修改此机制.

My data serialization checks every property and saves it in a specified way. I don't want to modify this mechanism.

当我从关系A获取一个对象时,就会出现问题.我从数据库层返回它,并将其传递给序列化.它试图访问对B和C的引用,但是当我们不在对象上下文之外时,它就无法完成.

The problem occurs, when I fetch an object from, let's say, relation A. I return it from my database layer and pass it to serialization. It tries to access the references to B and C, but while we're outside the object context, it cannot be done.

我知道我可以执行以下操作:

I know I can do the following:

AEntry a = db.A.FirstOrDefault(something);
a.BReference.Clear(); //(or .Load())
a.CReference.Clear();
return a;

但是我不喜欢这种解决方案.我正在寻找可以使我尽可能长时间保持未实现的"a"对象(或此类对象的集合)的东西,并且我不想打扰每个引用(因为可能有很多他们).

But I don't like this solution. I'm looking for something that would allow me to keep the 'a' object (or possibly a collection of such objects) unmaterialized as long as possible and I don't want to bother with every reference (as there may be a lot of them).

很明显,在这种情况下,我不在乎引用对象(或引用我获取的对象的对象)的内容.

Obviously, in this case I don't care about the content of referred objects (or objects referring to the object I fetch).

我希望我的问题很清楚.感谢您的帮助.

I hope my problem is quite clear. Thanks for help.

推荐答案

我认为您想转为延迟加载.请参阅此问题,或者设置您的ObjectContext:

I think you want to turn of lazy loading. See this question, either set the ContextOptions property of your ObjectContext:

context.ContextOptions.LazyLoadingEnabled = false; 

或者,如果您使用的是.edmx模型,请设置LazyLoadingEnabled批注:

Or, if you're using an .edmx model, set the LazyLoadingEnabled annotation:

<EntityContainer Name="MyEntitiesContext" annotation:LazyLoadingEnabled="false"> 

当然,您必须确保显式加载所需的数据,然后(使用 ObjectQuery 中的 Include()方法)代码>.

Of course, you will have to make sure that the data you do need is explicitly loaded then (using the Include() method on ObjectQuery.

这篇关于从数据库中选择浅对象,从外键中删除所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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