C#实体框架延迟加载(如果未分离) [英] C# Entity Framework lazy loading if not detached

查看:61
本文介绍了C#实体框架延迟加载(如果未分离)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对EntityFramework OnSave中的每个对象进行一些处理.此过程的一部分涉及将对象转换为Binary对象.永远需要序列化,而我大约99%的人认为这是因为我们在EntityFramework上使用了惰性加载,并且它捕获了在PartialClasses中访问的惰性加载对象.

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.

我尝试从ObjectContext分离对象,但是我的同事在整个应用程序中都使用了延迟加载,而没有先检查对象是否为NULL.

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.

例如,在部分类文件中有如下代码:
get { return this.ContactsTable.FullName; }
只要未分离对象,该方法就可以正常工作.分离后,我会得到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.

我的问题是:我是否可以分离对象并让延迟加载不引发Null引用异常,或者我是否可以告诉DataContractSerializer忽略延迟加载的对象?

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

否.

我可以告诉 DataContractSerializer忽略懒惰 加载的对象

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

否.

但是应该有简单的解决方案.当您要序列化实体时,请在附加实体的上下文中调用它:

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.

这篇关于C#实体框架延迟加载(如果未分离)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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