【发布时间】:2018-01-22 13:28:53
【问题描述】:
我有以下代码,我尝试获取所有学生(UserTypeID = 2)
using SchoolData;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace SchoolAPI.Controllers
{
public class StudentsController : ApiController
{
public List<User> Get()
{
using(SchoolEntities DB = new SchoolEntities())
{
var L = DB.Users.Where(u => u.UserTypeID == 2).ToList();
return L;
}
}
public User Get(int id)
{
using(SchoolEntities DB = new SchoolEntities())
{
return DB.Users.Where(u => u.UserTypeID == 2).FirstOrDefault(u => u.UID == id);
}
}
}
}
当我在启用延迟加载的情况下运行此代码时,我尝试通过函数 Get() 获取所有学生,它会引发错误:
"Message": "An error has occurred.",
"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": null,
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Error getting value from 'City' on 'System.Data.Entity.DynamicProxies.User_43D4A249734A75DBA5AC314F4FE462E834BDC252CC9384BF940FE65C74CE3D08'
和
"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
当我尝试禁用惰性模式并重新运行时,它会正确获取对象,但带有一些额外的不需要的参数,如下所示:
{
"City": null,
"CourseDetails": [],
"StudentsCourses": [],
"UserType": null,
"UID": 2,
"FName": "Ahmed",
"LName": "Mano",
"Birthdate": "1995-05-27T00:00:00",
"CityID": 1,
"UserTypeID": 2
}
我既不需要 CourseDetails、StudentsCourses、City 也不需要 UserType
【问题讨论】:
-
因为序列化器在
using语句引入的作用域结束数据库交互之后任意遍历对象。它与您的查询没有直接关系,因为它们序列化程序无论如何都必须具体化整个图。通常使用专用的响应类型来处理这种情况。一个更广泛的看待这个问题的方法是思考在延迟加载下访问聚合属性的开放连接的要求在类型系统中是无法表达的,至少这是看待它的一种方式。
标签: c# entity-framework asp.net-mvc-5 lazy-loading eager-loading