'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'

'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'

这个问题已经被问过很多次了。我想我解决了我的问题,但由于我是初学者并且仍在学习,我需要你的保证。

我为登录用户创建了一个扩展方法,但是当我在我的控制器中使用它时,它给了我标题错误。

System.ObjectDisposedException: 'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'

所以我搜索并试验并添加了这行代码 在控制器中解决了我的问题。

db.Users.Attach(LoggedUser);

但是我不确定我的回答是否正确,因为关于这个问题的很多答案都是禁用延迟加载,但我最终没有使用它。

类似这样。

public class MyDbContext : DbContext
{
  public MyDbContext()
   {
    this.Configuration.LazyLoadingEnabled = false;
   }
}

这是我的扩展方法:

 public static ApplicationUser GetLoggedInUserInDB(this System.Security.Principal.IPrincipal _User)
    {
        using (var db = new ApplicationDbContext())
        {
            string userId = _User.Identity.GetUserId();
            var LoggedUser = db.Users.Find(userId);
            return LoggedUser;
        }
    }

我的控制器:

public class MainPageController : ApiController
{
    [Route("Personal_Project/Main_Page_Personal_Project/UserUnfo")]
    [ResponseType(typeof(string))]
    [Authorize]
    public IHttpActionResult GetUserInfo()
    {
        using (var db = new ApplicationDbContext())
        {
            var LoggedUser = User.GetLoggedInUserInDB();
            //db.Users.Attach(LoggedUser); // This is what I added to solve my problem.
            return Ok(new UserInfoModel
            {
                Name = LoggedUser.UserName,
                Reputation = LoggedUser.Reputation,
                UserLevel = LoggedUser.UserLevel
            });
        }
    }
}

那么'My'这里的解决方案好吗?只需添加:

db.Users.Attach(LoggedUser);

这是合法的还是这不是我们解决这个问题的方法。任何建议将不胜感激

按要求添加:

堆栈跟踪:

ex.StackTrace " at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityReference1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.b__2(TProxy proxy, TItem item)\r\n at System.Data.Entity.DynamicProxies.ApplicationUser_3D8410FBA1701532D53558B4E07B366CC45F4901DA609FCE10D652D704EEDD3C.get_CarGame()\r\n at PersonalProject.Controllers.MainPageController.GetUserInfo() in C:\Users\Jack\Desktop\PostPersonalProject\PersonalProject\PersonalProject\Controllers\MainPageController.cs:line 32" string

您因此而出现异常:get_CarGame()

原始 post 中的代码与您的实际代码不匹配。

actual MainPageController.GetUserInfo 的某处,您正在尝试阅读 ApplicationUser.CarGame。是的,这是延迟加载问题。

GetLoggedInUserInDB returns 代理 class 的实例,派生自 ApplicationUser,并配置原始上下文。当 GetUserInfo 尝试获取 CarGame 属性 值时,代理会尝试使用处置上下文从数据库中读取它。结果,抛出异常。

如果你真的需要CarGame里面UserInfoModel:

  • 要么如上所示关闭延迟加载,而使用预加载;
  • 使用投影(即 Select)将用户信息检索为 UserInfoModel。在这种情况下,根本不需要 GetLoggedInUserInDB 方法。

无论如何,将 LoggedUser 附加到另一个上下文不是可行的方法。