C# Entity Framework lazy loading if not detached

痴心易碎 提交于 2019-12-11 04:26:01

问题


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 over 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?


回答1:


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.



来源:https://stackoverflow.com/questions/6159364/c-sharp-entity-framework-lazy-loading-if-not-detached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!