实体框架懒加载 [英] Entity Framework lazy loading

查看:225
本文介绍了实体框架懒加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using(DataContext db = new DataContext ())
{
    var result = db.SomeTable.ToList();
    return result;
}

问题是在我返回结果后,连接已关闭,因为它的关闭,当我尝试访问任何子元素时,它崩溃。这是因为使用惰性加载设置为True(默认),它在使用之前从不加载子关系,并且在连接关闭后我开始使用它们。那么最好的方法是如何解决这个问题?

Problem is after i have returned the result, the connection is closed and because its closed, it crashes when i am trying to access any of the child elements. That happens because with lazy loading set to True ( default ) it never loads the child relations before they are used and i start using them AFTER the connection is closed. So how is the best way to solve this?

我试图关闭懒惰加载,但是它没有加载任何一个子关系表。

I have tried to turn off the lazy loading but then it didnt load any of the child relation tables.

推荐答案

您可以随时显式加载您的子集合:

You can always explicitly load your child collections:

var result = db.SomeTable.Include("SomeChildCollectionName")
                         .Include("AnotherChildCollectionName")
                         .ToList();

这篇关于实体框架懒加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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