linq延迟加载的问题

使用Linq的时候常会遇到延迟加载带来的问题,比如2个表class(id,name),student(id,classId,name)

当从数据层取到某个student对象后,想要取他对应的班级的名称,则会报上下文环境以被释放的错误!

代码如下:

数据层: 

         public student getStudentById(int id)

        {  

           using(DBDataContext dc = new DBDataContext())

            {

                student st = dc.students.single(s=>s.id==id);

                return st;

             }

         }

上层使用getStudentById:

          student st = **.getStudentById(id);//**为数据层getStudentById所在的类对象名

          string className = st.class.name;//抛出异常!上下文被释放!

解决方法,可以在数据层显示获取className

如:getStudentById方法中返回st之前,加入:st.class.name = st.class.name;即可

转载于:https://www.cnblogs.com/JasonCrab/archive/2009/07/02/1515740.html

猜你喜欢

转载自blog.csdn.net/weixin_33690963/article/details/94278728