1

In my app, 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.

Piotr Zierhoffer
  • 5,005
  • 1
  • 38
  • 59

1 Answers1

1

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.

Community
  • 1
  • 1
jeroenh
  • 26,362
  • 10
  • 73
  • 104
  • Thank you, maybe it's not exactly what I want (Include is not my favorite choice), but it will solve the issue. As I understand, these ContextOptions are set per ObjectContext instance, not whole connection, so it will do the trick! – Piotr Zierhoffer Sep 20 '11 at 13:40