开发者

Select shallow object from database, dropping all references from foreign keys

开发者 https://www.devze.com 2023-04-06 08:53 出处:网络
In my app开发者_StackOverflow社区, I frequently fetch some data from database, serialize it automatically and then send it somewhere.

In my app开发者_StackOverflow社区, I frequently fetch some data from database, serialize it automatically and then send it somewhere.

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

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.

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;

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.


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

context.ContextOptions.LazyLoadingEnabled = false; 

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

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号