开发者

C# Entity Framework lazy loading if not detached

I am trying to do some process against every object in my EntityFramework OnSave. Part of this process involves turning the object into a Binary object. It is taking FOREVER to Serialize and I am about 99% positive that it is because we are using Lazy Loading on our EntityFramework and it is grabbing Lazy Loaded objects that are accessed in PartialClasses.

I tried detaching my object from the ObjectContext, but my coworkers have used Lazy Loading all o开发者_运维问答ver our application without first checking if the object was NULL.

For example, there is code like this in our Partial Classes file:

get { return this.ContactsTable.FullName; }

That works fine as long as the object is not Detached. As soon as it is detached I get Null reference errors.

My question is this: Is it possible for me to detach my object and have Lazy Loading not throw Null Reference exceptions, OR is it possible for me to tell the DataContractSerializer to ignore Lazy Loaded objects?


Is it possible for me to detach my object and have Lazy Loading not throw Null Reference exceptions

No.

is it possible for me to tell the DataContractSerializer to ignore Lazy Loaded objects

No.

But there should be simple solution. When you go to serialize the entity call this on the context where the entity is attached:

// Turn off the lazy loading
context.ContextOptions.LazyLoadingEnabled = false;
// Run your serialization here
...
// Turn on the lazy loading again
context.ContextOptions.LazyLoadingEnabled = true;

But it is whole very strange because serialization will try to serialize all loaded entities and by your description it looks like you never know how big part of the object graph will be serialized.

If you really want to save only single object detaching is way to go but it will break all relations with other objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜