简体   繁体   English

延迟加载框架实体的问题

[英]Issue with lazy loading Framework Entity

I am using Entity with lazy loading and I have to following problem, I'm running a query that doesn't include related properties but when I try to serialize the object, serializer is trying to load the related properties and since my context is disposed I'm getting an exception. 我正在使用延迟加载的Entity,但我必须解决以下问题,我正在运行一个不包含相关属性的查询,但是当我尝试序列化对象时,序列化程序正在尝试加载相关属性,并且由于我的上下文已被处置我要例外了。

What I want to do is set all related properties to null when they are not loaded (some times I might include them in my query and I'd like them to be serialized in that case). 我想做的是在未加载所有相关属性时将其设置为null(有时我可能会将它们包含在查询中,并且在这种情况下我希望将它们序列化)。 Is there a way I can do that? 有办法吗?

Try following code. 尝试以下代码。 I use Json.Net for serialization, and set LazyLoadingEnabled = false. 我使用Json.Net进行序列化,并设置LazyLoadingEnabled = false。

using (var dbContext = new ApplicationDbContext())
{
    dbContext.Configuration.LazyLoadingEnabled = false;

    var list = dbContext.Videos.Take(5).ToList();

    var output = JsonConvert.SerializeObject(list);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM